我們都知道,AJAX的一大限制是不允許跨域請求。 不過通過使用JSONP來實現。JSONP是一種通過腳本標記注入的方式,它是可以引用跨域URL的js腳本,不過需要提供一個回調函數(必須在您自己的頁面上),因此,你可以自己處理結果。 讓我們看看JSONP的是怎么在jQuery,MooTools的,Dojo Toolkit中實現的。
jQuery的JSONP
jQuery.getJSON方法:
Js代碼
復制代碼 代碼如下:
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{
q: "Arsenal"
},function(tweets) {
// Handle response here
console.info("Twitter returned: ",tweets);
});
復制代碼 代碼如下:
$.ajax({
type:"get",
data:"random="+Math.random(),
url:url,
dataType:"jsonp",
jsonp:"callback",
success:function(data){
$.each(data, function(key, val) {
$("#myDiv").html($("#myDiv").html()+val.cvalue+"</br>");
});
}
});
復制代碼 代碼如下:
new Request.JSONP({
url: "http://search.twitter.com/search.json",
data: {
q: "Arsenal"
},//提交的參數, 沒有參數可以不寫
callbackKey: 'jsoncallback',//自己定義回調函數的參數名稱
onComplete: function(tweets) {
// Log the result to console for inspection
console.info("Twitter returned: ",tweets);
}
}).send();
復制代碼 代碼如下:
String callback = request.getParameter("jsoncallback");//取得回調方法名
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.print(callback+"("+message+")");//這里是關鍵.主要就是這里
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
復制代碼 代碼如下:
// dojo.io.script is an external dependency, so it must be required
dojo.require("dojo.io.script");
// When the resource is ready
dojo.ready(function() {
// Use the get method
dojo.io.script.get({
// The URL to get JSON from Twitter
url: "http://search.twitter.com/search.json",
// The callback paramater
callbackParamName: "callback", // Twitter requires "callback"
// The content to send
content: {
q: "Arsenal"
},
// The success callback
load: function(tweetsJson) { // Twitter sent us information!
// Log the result to console for inspection
console.info("Twitter returned: ",tweetsJson);
}
});
});
|
新聞熱點
疑難解答
圖片精選