开发者

Reading a JSON object

I have a Service which returns JSON using C#'s JavaScriptSerializer class.

jQuery

        $.get('GlobalService/Index',
            { crudOperation: crudOperation,
                globalType: globalType,
                globalObject: globalObject
            },
            function (data) {
                alert(data);
    开发者_如何学Python        });

the callback function displays in the alert

[object XMLDocument]

How do I get to and parse the JSON object? The object has basic construction

{"field1":"data","field2":"more data",/*...~10 more of these*/}


$.get('GlobalService/Index',
{ 
    crudOperation: crudOperation,
    globalType: globalType,
    globalObject: globalObject
},
function (data) {
    // access it as you would normally access a JS object
    alert(data.field1);
}, 
'json'); // do not forget to pass the json data type here, otherwise it 
         // will just guess it (probably wrong, as it shows in your case)


Easiest way. @see getJSON

also,

parseJSON


Your code is working fine, just an alert cannot show the object data:

    $.get('GlobalService/Index',
        { crudOperation: crudOperation,
            globalType: globalType,
            globalObject: globalObject
        },
        function (data) {
            console.log(data); //view data in console
            alert(data.field1);
        });


You must specify a dataType of "json" in order to let the method know how parse the returned data:

      $.get('GlobalService/Index',
            { crudOperation: crudOperation,
                globalType: globalType,
                globalObject: globalObject
            },
            function (data) {
                alert(data);
            }, 'json');

See $.get() documentation at jQuery: http://api.jquery.com/jQuery.get/.

Note that if you don't specify dataType, jQuery will do a smart guess of what the server is returning and it is very clear that it is misunderstanding the server response with an XML block of code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜