如何使用jquery处理json数据

a 夏天 提交于 2019-11-30 14:07:09

    如摘要所说,json是常用的前后端交互的数据格式,本文简单介绍jquery如何解析json数据,以备忘。

如下是一个嵌套的json:

[{"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() 可以实现.

    

下面引用的是官方API对$.getJSON()的说明:

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

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

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

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

回调函数中接受三个参数,第一个书返回的数据,第二个是状态,第三个是jQuery的XMLHttpRequest,我们只使用到第一个参数。

$.each()是用来在回调函数中解析JSON数据的方法,下面是官方文档:

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;
}



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!