格式:jQuery.getJSON( url [,data] [,success(data,textStatus,jqXHR)] ), 三个参数分别死请求地址, 要传递的参数, 回调函数
This is a shorthand Ajax function,which is equivalent to:@H_502_7@
$.ajax({@H_502_7@
url: @H_502_7@url@H_502_7@,@H_502_7@
dataType: 'json',@H_502_7@
data: @H_502_7@data@H_502_7@,@H_502_7@
success: @H_502_7@callback@H_502_7@
});@H_502_7@
@H_502_7@
@H_502_7@
The@H_502_7@success@H_502_7@
@H_502_7@callback is passed the returned data,whichis typically a JavaScript object or array as defined by the JSON structure and parsed using the@H_502_7@$.parseJSON()@H_502_7@
@H_502_7@method. It is also passed the text status of the response.@H_502_7@
@H_502_7@
As of jQuery 1.5@H_502_7@,the@H_502_7@success@H_502_7@
@H_502_7@callback function receives a@H_502_7@"jqXHR" object@H_502_7@(in@H_502_7@jQuery1.4,it received theXMLHttpRequest@H_502_7@
@H_502_7@object). However,since JSONP and cross-domain GET requests do not use@H_502_7@XHR,in those cases thejqXHR
andtextStatus
parameters passed to the success callback are undefined.
如果在服务器端没有指定返回数据的格式, 我们可以讲返回值使用$.parseJSON()@H_502_7@处理一下, 如果在服务器端已经处理, 那么在函数中可以直接使用。比如:@H_502_7@@H_502_7@@H_502_7@@H_502_7@
在服务器端的代码:@H_502_7@@H_502_7@@H_502_7@@H_502_7@
<%
response.setContentType("text/json");
out.println("[{\"name\":\"湖南省\",\"regionId\":134},{\"name\":\"北京市\",\"regionId\":143}]");
%>
@H_502_7@
注意:格式良好的JSON应该使用双引号讲字符串括起来。否则可能在解析的出错!@H_502_7@
@H_502_7@
@H_502_7@
$.getJSON("http://localhost:8080/jqueryTest2",
@H_502_7@function(json){
@H_502_7@alert(json[0].name);
@H_502_7@alert(json[1].name);
@H_502_7@});
@H_502_7@
response.setContentType("text/json");@H_502_7@
@H_502_7@
那么在回调函数中要对返回的数据进行处理:@H_502_7@@H_502_7@
$.getJSON("http://localhost:8080/jqueryTest2",@H_502_7@
@H_502_7@function(json){ @H_502_7@@H_502_7@@H_502_7@
json=$.parseJSON(json);@H_502_7@@H_502_7@
alert(json[0].name);@H_502_7@
alert(json[1].name);@H_502_7@
}); @H_502_7@
@H_502_7@@H_502_7@
$.parseJSON()方法可以将一个JSON格式的字符串解析为对象。@H_502_7@
@H_502_7@@H_502_7@@H_502_7@
@H_502_7@
继续,@H_502_7@
在jquery1.5中, 回调函数会接收XMLHttpRequest对象,@H_502_7@@H_502_7@@H_502_7@
jsonp和跨域的get请求没有使用XMLHttpRequest对象(为什么?),所以jQuery.getJSON( url [,jqXHR)] )中的参数jqXHR@H_502_7@
和@H_502_7@@H_502_7@textStatus在回调函数中是undefined类型的。@H_502_7@
@H_502_7@@H_502_7@@H_502_7@@H_502_7@
@H_502_7@
Additional Notes:
- Due to browser security restrictions,most "Ajax" requests are subject to thesame origin policy; the request can not successfully retrieve data from a different domain,subdomain,or protocol.
- Script and JSONP requests are not subject to the same origin policy restrictions.
@H_502_7@
@H_502_7@
JSONP
If the URL includes the string "callback=?" (or similar,as defined by the server-side API),the request is treated as JSONP instead. See the discussion of thejsonp
data type in$.ajax()
for more details.
@H_502_7@