Jquery Ajax方法使用多个json对象但不使用单个json对象

时间:2013-07-20 18:47:32

标签: jquery ajax json

当我发送json对象数组时,我的jquery ajax方法能够解析内容并在jquery的listview中显示数据,但是当我只有一个单个对象时,我的jquery ajax方法无法解析数据。

这里是我的json对象数组:

{"menuService":[{"idmenu":"0","itemCatagory":"Main Course","itemDescription":"Food from UP","itemImagePath":"http://localhost:8080/fotservice/ItemImage?id=Steam Rice","itemName":"Steam Rice","rate":"100.5","subItemName":"Half Plate Steam Rice","subItemNameRate":"100.5"},{"idmenu":"5","itemCatagory":"Main Course","itemDescription":"tasty lunch","itemImagePath":"http://localhost:8080/fotservice/ItemImage?id=Lunch Combo(raita,rice,dal,salad)","itemName":"Lunch Combo(raita,rice,dal,salad)","rate":"123.0","subItemName":"lunch(dal,rice)","subItemNameRate":"100.5"}]}

这是我的单个json对象:

{"menuService":{"idmenu":"2","itemCatagory":"xyz","itemDescription":"fghjkl;","itemImagePath":"http://localhost:8080/fotservice/ItemImage?id=Dal makhni","itemName":"Dal makhni","rate":"121.5","subItemName":"Half plate Dal makhni","subItemNameRate":"121.56"}}

这是我的jquery ajax方法:

$.ajax({
    url: "http://localhost:8080/fotservice/rest/menu/"+cat+"/items",  
    type: 'GET',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function( response ) {
        var markup = "";
        $.each(response.menuService, function(index, result) { 
            var $template = $('<div><li> <a data-transition="slide" href="desc.html?cat='+result.itemName+'" rel="external" > <img class="profile"> <p class="from"> </p><p class="tweet"> </p></li></a></div>');
            $template.find(".profile").attr("src", result.itemImagePath);
            $template.find(".from").append(result.itemDescription);

            markup += $template.html();
        });
        $( "#tweet-list" ).append(markup).listview( "refresh", true ); // The true parameter indicates we want to refresh the entire list, not just the list items. 

    },
    timeout: 6000,  // Timeout after 6 seconds
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("Error, textStatus: " + textStatus + " errorThrown: "+ errorThrown);

        $.mobile.hidePageLoadingMsg();

        //show error message
        $( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" )
            .css({ "display": "block", "opacity": 0.96, "top": 100 })
            .appendTo( $.mobile.pageContainer )
            .delay( 800 )
            .fadeOut( 1000, function() {
                $( this ).remove();
            });
    }
});

我尝试了jquery getjson方法,但这也是同样的行为。

4 个答案:

答案 0 :(得分:0)

var mns = response.menuService;

if (mns&& !mns.length) mns=[mns];
$.each(mns...

答案 1 :(得分:0)

检查response.menuService是否是一个带有jquery类型的数组,如果你不是这样做的话:

var success = function(response) {
    var markup = "";
    var arrayResponse;
    console.log(response.menuService);
    if ($.type(response.menuService) !== 'array') {
        var arrayResponse = [];
        arrayResponse.push(response.menuService);
    } else {
        arrayResponse = response.menuService; 
    }
    console.log(arrayResponse);
    $.each(arrayResponse, function(index, result) { 
        $('#list').append('<div>' + result.idmenu + '</div>');
    });
};

var response = {"menuService":[{"idmenu":"0"}]};

success(response);

var response = {"menuService":{"idmenu":"2"}};

success(response);

我做了一个小提琴,以便你可以测试它:http://jsfiddle.net/U72p2/

答案 2 :(得分:0)

您可以检查它是否是Array.isArray的数组,如果不是,请将其包装在数组中,以便$.each能够正常工作

success: function( response ) {
    var markup = "";
    var menuService = Array.isArray(response.menuService) ? response.menuService : [response.menuService];

    $.each(menuService, function(index, result) { 
        ...
    });

    ...

答案 3 :(得分:0)

像这样更改json格式并尝试

{"menuService":[{"idmenu":"2","itemCatagory":"xyz","itemDescription":"fghjkl;","itemImagePath":"http://localhost:8080/fotservice/ItemImage?id=Dal makhni","itemName":"Dal makhni","rate":"121.5","subItemName":"Half plate Dal makhni","subItemNameRate":"121.56"}]}

或者不要使用each并直接访问该值

response.menuService.itemImagePath

如果您使用相同的json格式,请按以下步骤更新success处理程序:

success: function(response) {
    var markup = "";
    var $template = $('<div><li> <a data-transition="slide" href="desc.html?cat=' + response.menuService.itemName + '" rel="external" > <img class="profile"> <p class="from"> </p><p class="tweet"> </p></li></a></div>');
    $template.find(".profile").attr("src", response.menuService.itemImagePath);
    $template.find(".from").append(response.menuService.itemDescription);
    markup += $template.html();
    $("#tweet-list").append(markup).listview("refresh", true); // The true parameter indicates we want to refresh the entire list, not just the list items. 
}