我有一个使用C#的JavaScriptSerializer
类返回JSON的服务。
的jQuery
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
});
回调功能显示在警报
中[object XMLDocument]
如何进入并解析JSON对象?该对象具有基本结构
{"field1":"data","field2":"more data",/*...~10 more of these*/}
答案 0 :(得分:3)
$.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)
答案 1 :(得分:2)
答案 2 :(得分:2)
您的代码工作正常,只是警报无法显示对象数据:
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
console.log(data); //view data in console
alert(data.field1);
});
答案 3 :(得分:1)
您必须指定{{1>}“ json ”才能让方法知道如何解析返回的数据:
dataType
请参阅jQuery上的$ .get()文档:http://api.jquery.com/jQuery.get/。
请注意,如果您未指定 $.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
}, 'json');
,jQuery将对服务器返回的内容进行 智能猜测 ,并且它非常清楚它是用XML代码块误解服务器响应。