如何使用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;
}
相关文章
相关标签/搜索