开发者

jQuery Parse JSON Array

OK so this is driving me insane.. I'm attempting to parse JSON from a web method into a <ul>, here's what I've got:

function searchPostcode() {
    var search = $("#txtPostcode").attr("value");
    //alert(search);
    $.ajax({
        type: "POST",
        url: "DeliverySettings.aspx/getDeliveryInfoForPostcode",
        contentType: "application/json; charset=utf-8",
        data: "{'postcode':'" + search + "'}",
        dataType: "json",
        success: AjaxSucceeded,
        error: AjaxFailed
    });

    function AjaxSucceeded(result) {
        var items = [];

        $.each(eval(result), fun开发者_如何转开发ction (key, val) {
            items.push('<li id="' + key + '">' + val + '</li>');
        });

        $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
        }).appendTo('jsonresults');

    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }
}

And here's a sample of the JSON returned from the WebMethod:

[{"Name":"Full Pallet","Price":"90.0000"},{"Name":"Half Pallet","Price":"60.0000"},{"Name":"Quarter Pallet","Price":"40.0000"},{"Name":"Small Parcel","Price":"30.0000"},{"Name":"Medium Parcel","Price":"20.0000"},{"Name":"Large Parcel","Price":"10.0000"}]

I've tried with and without the eval to no avail, I just cant get into a list... Please help! :)


What is jsonresults? If it's an ID, you forgot the #

.appendTo('#jsonresults');

Also, with this:

items.push('<li id="' + key + '">' + val + '</li>');

you'll get [object Object] as the text content. I assume you want the Name. If so, do this:

items.push('<li id="' + key + '">' + val.Name + '</li>');

Also keep in mind that the key is the index of the Array. If you're supporting HTML4, it isn't valid to have an ID that starts with a number.

You may want to change it to:

items.push('<li id=product_"' + key + '">' + val.Name + '</li>');

...or something similar.

Example: http://jsfiddle.net/G8HqX/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜