如何使用jquery處理json數據

    如摘要所說,json是經常使用的先後端交互的數據格式,本文簡單介紹jquery如何解析json數據,以備忘。javascript

以下是一個嵌套的json:
html

[{"name":"20:00-21:15","price":"1.00"},{"name":"17:30-17:59","price":"1.00"},
{"name":"22:00-22:30","price":"3.00"},{"name":"20:00-21:15&22:00-22:30","price":"0.00"}]

1.在jQuery中有一個簡單的方法 $.getJSON() 能夠實現.java

    

下面引用的是官方API對$.getJSON()的說明:jquery

jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )

urlA string containing the URL to which the request is sent.web

dataA map or string that is sent to the server with the request.ajax

success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.json

回調函數中接受三個參數,第一個書返回的數據,第二個是狀態,第三個是jQuery的XMLHttpRequest,咱們只使用到第一個參數。後端

$.each()是用來在回調函數中解析JSON數據的方法,下面是官方文檔:app

jQuery.each( collection, callback(indexInArray, valueOfElement) )

collectionThe object or array to iterate over.函數

callback(indexInArray, valueOfElement)The function that will be executed on every object.


$.each()方法接受兩個參數,第一個是須要遍歷的對象集合(JSON對象集合),第二個是用來遍歷的方法,這個方法又接受兩個參數,第一個是遍歷的index,第二個是當前遍歷的值


function loadInfo() {
    $.getJSON("loadInfo", function(data) {
        $("#info").html("");//
        $.each(data.comments, function(i, item) {
            $("#info").append('<option value="'    +item.price+     '">'     
          +item.name+    '</option>');
        });
        });
}

2.或者不用$.getJSON而使用$.ajax獲取返回數據的時候使用eval解析,例如

pricejson = eval(msg);

                         var    salehtml = '';
                           $.each(pricejson, function(i, item) 
                         {                                 
                               salehtml  += '<option value="'    +item.price+     '">'     +item.name+    '</option>'; 
                          }); 
$("#info").html(salehtml);


PS: 原生javascript處理客戶端js接收返回數據的時候,有時候服務端有可能返回空的對像,

好比:

var data = ({});

isEmptyObject: function( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}
相關文章
相關標籤/搜索