发布在:Ajax

使用 JSONP

JSONP 的出现(本质上是一种协商式跨站点脚本攻击)为内容的强大混搭打开了大门。许多知名网站提供 JSONP 服务,允许你通过预定义的 API 访问其内容。JSONP 格式数据的特别好来源是 Yahoo! 查询语言,我们将在以下示例中使用它来获取有关猫的新闻。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell YQL what we want and that we want JSON
data: {
q: "select title,abstract,url from search.news where query=\"cat\"",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});

jQuery 在后台处理 JSONP 的所有复杂方面——我们所要做的就是告诉 jQuery 由 YQL 指定的 JSONP 回调参数的名称(在本例中为“callback”),否则整个过程看起来和感觉就像一个正常的 Ajax 请求。