我想用以下代码用jquery ajax解析JSON数组数据:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sample</title> <script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script> <script type="text/javascript"> var result; function jsonparser1() { $.ajax({ type: "GET", url: "http://10.211.2.219:8080/SampleWebService/sample.do", dataType: "jsonp", success: function (xml) { alert(xml.data[0].city); result = xml.code; document.myform.result1.value = result; }, }); } </script> </head> <body> <p id="details"></p> <form name="myform"> <input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() /> <input type="text" name="result1" readonly="true"/> </form> </body> </html>
我的JSON数据是:
{"Data": [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}
但是我没有任何输出…任何人请帮忙…
您是否正在尝试进行跨域AJAX调用?意思是,您的服务不在同一Web应用程序路径中托管吗?您的Web服务必须支持方法注入才能执行JSONP。
您的代码看起来不错,并且如果您的Web服务和Web应用程序托管在同一域中,则该代码应该可以正常工作。
当您执行时$.ajax,dataType: 'jsonp'意味着jQuery实际上是在查询URL中添加一个新参数。
$.ajax
dataType: 'jsonp'
例如,如果您的URL为,http://10.211.2.219:8080/SampleWebService/sample.do则jQuery将添加?callback={some_random_dynamically_generated_method}。
http://10.211.2.219:8080/SampleWebService/sample.do
?callback={some_random_dynamically_generated_method}
这种方法实际上是window对象中附加的一种代理。这没有什么特别的,但确实是这样的:
window
window.some_random_dynamically_generated_method = function(actualJsonpData) { //here actually has reference to the success function mentioned with $.ajax //so it just calls the success method like this: successCallback(actualJsonData); }
摘要
您的客户端代码似乎很好。但是,您必须修改服务器代码以使用通过查询字符串传递的函数名称包装JSON数据。即
如果您要求查询字符串
?callback=my_callback_method
然后,您的服务器必须响应包装如下的数据:
my_callback_method({your json serialized data});