jQuery.getJSON()

格式:jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] ), 三个参数分别死请求地址, 要传递的参数, 回调函数


This is a shorthand Ajax function, which is equivalent to:

$.ajax({

  url: url,

  dataType: 'json',

  data: data,

  success: callback

});

也就是说, jQuery.getJSON()方法是 $.ajax()的简略形式。


The success callback is passed the returned data, whichis typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are  undefined.




这是说, 服务器端的返回值传递给回调函数,  服务器端的返回值是个JSON结构的javascript对象或者数组。

如果在服务器端没有指定返回数据的格式, 我们可以讲返回值使用$.parseJSON()  处理一下, 如果在服务器端已经处理, 那么在函数中可以直接使用。比如:

在服务器端的代码:

<%
response.setContentType("text/json");
out.println("[{\"name\":\"湖南省\",\"regionId\":134},{\"name\":\"北京市\",\"regionId\":143}]");
 %>

注意:格式良好的JSON应该使用双引号讲字符串括起来。否则可能在解析的出错!



这时, 回调函数中可以直接使用:

$.getJSON("http://localhost:8080/jqueryTest2",
function(json){   
alert(json[0].name);
alert(json[1].name);
});  

如果在服务端没有这句:

response.setContentType("text/json");

那么在回调函数中要对返回的数据进行处理:

$.getJSON("http://localhost:8080/jqueryTest2",
function(json){   

              json=$.parseJSON(json); 

alert(json[0].name);
alert(json[1].name);
});  

$.parseJSON()方法可以将一个JSON格式的字符串解析为对象。 


继续, 

在jquery1.5中, 回调函数会接收XMLHttpRequest对象, 

jsonp和跨域的get请求没有使用XMLHttpRequest对象(为什么?), 所以jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )中的参数jqXHR 和 textStatus在回调函数中是undefined类型的。

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same 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.
这是说, 大部分ajax请求由于同源策略而受到限制, 导致请求不能够成功从其他域获取数据, 所谓非同域指的是:不同的域名之间, 子域名和上级域名之间,以及不同协议的域名之间。


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 the jsonp data type in $.ajax()for more details.

如果在jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )的URL后面跟上callback=?, 那么这个请求会被认为死JSONP, 也就是说, 这个方法是可以跨域的。

关于跨域, 下一篇再总结。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值