May 08, 2021 JSON
XMLHttpRequest
an API that allows client JavaScript to connect to a remote server over HTTP.
Ajax is also the driving force behind many mashups that integrate content from multiple locations into a single web application.
As we all know, AJAX is not allowed to cross-domain requests due to browser restrictions. H owever, this can be done by using JSONP. J SONP is a way of injecting through script tags, it is a js script that can reference cross-domain URLs, but you need to provide a callback function (which must be on your own page), so you can handle the results yourself. T his article describes how JSONP is implemented in jQuery, MooTools, Dojo Toolkit.
To understand JSONP, you have to mention JSON, so what is JSON?
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
JSON with Padding is an unofficial protocol that allows the server-side integration of Script tags back to the client side for cross-domain access in the form of javascript callback (this is just a simple implementation of JSONP).
Due to the limitations of the same source policy, XmlHttpRequest only allows requests for resources from the current source (domain name, protocol, port), and in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then the JSON data is output on the service side and callback functions are performed, thus resolving cross-domain data requests.
jQuery.getJSON method:
The Js code is as follows:
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{
q: "Arsenal"
},function(tweets) {
// Handle response here
console.info("Twitter returned: ",tweets);
});
Or something like that
The Js code is as follows:
$.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>");
});
}
});
The parameters of the callback method can be obtained from the json object through getJSON
MooTools requires Request.JSONP Class, from which you can download MooTools More. Select Request.JSONP
Getting JSON from another domain is a piece of cake
The Js code is as follows:
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();
If you define the parameter name of the callback function yourself, it's the same as jquery
On the server side you need to go this way to get:
The Js code is as follows:
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();
}
By the way: individuals prefer the grammatical structure of mootools, and frame design ideas, praise again!
JSONP needs dojo.io.script in Dojo Toolkit (click to see example)
The Js code is as follows:
// 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);
}
});
});
JSONP is a very effective, reliable and easy-to-implement way to obtain remote data. J
SONP's strategy also allows developers to avoid cumbersome server proxy methods and easily obtain data.
JSON with Padding is an unofficial protocol that allows the server-side integration of Script tags back to the client side for cross-domain access in the form of javascript callback (this is just a simple implementation of JSONP).
Client code:
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type="text/javascript">
function jsonpCallback(result) {
//alert(result);
for(var i in result) {
alert(i+":"+result[i]); //循环输出a:1, b:2, etc.
}
}
var JSONP=document.createElement("script");
JSONP.type = "text/javascript";
JSONP.src = "http://crossdomain.com/services.php?callback = jsonpCallback";
document.getElementsByTagName("head")[0].appendChild(JSONP);
</script>
Service-side code:
<?php
//服务端返回 JSON 数据
$arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
$result=json_encode($arr);
//echo $_GET['callback'].'("Hello,World!")';
//echo $_GET['callback']."($result)";
//动态执行回调函数
$callback = $_GET['callback'];
echo $callback."($result)";