I. JSON and jsonp
The full name of jsonp is JSON with padding. Due to the restrictions of the same-source policy, XMLHttpRequest only allows requests to resources of the Current Source (protocol, domain name, port. For cross-origin requests, we can use the HTML Script tag to perform cross-origin requests and return the script to be executed in the corresponding response.Code, Where JavaScript objects can be directly transmitted using JSON. This cross-origin communication method becomes jsonp.
From this we can see the difference between the two:
JSON: a lightweight data format.
Jsonp: a script injection method used to implement cross-origin.
Note: For more information about JSON, refer to the previous section about JSONArticle:JSON-related events
II. Implementation
For the sake of simplicity, we want to read all the data
VaRData = {'name': 'jifeng', 'company': 'taobao '};
1. server code:
VaR HTTP = require ( ' HTTP ' );
VaR Urllib = require ( ' URL ' );
VaR Port = 10011 ;
VaR Data = {' Name ' : ' Jifeng ' , ' Company ' : ' Taobao ' };
HTTP. createserver (function (req, Res ){
VaR Params = Urllib. parse (req. url,True );
Console. Log ( Params );
If ( Params . Query && Params . Query. Callback ){
// Console. Log (Params. query. Callback );
VaR STR = Params . Query. Callback + ' ( ' + JSON. stringify (data) + ' ) ' ; // Jsonp
Res. End (STR );
} Else {
Res. End (JSON. stringify (data )); // Common JSON
}
}). Listen (port, function (){
Console. Log ( ' Server is listening on port ' + Port );
})
2. the browser Code. For convenience, I directly used the jquery method.
<HTML>
<Head>
<SCRIPT src = "http://code.jquery.com/jquery-latest.js"> </SCRIPT>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
</Head>
<Body>
<SCRIPT type = "text/JavaScript">
FunctionGet_jsonp (){
$. Getjson ("http: // 10.232.36.110: 10011? Callback =? ",
Function(Data ){
$ ('# Result'). Val ('My name is:' + data. Name );
});
}
</SCRIPT>
<A href = "javascript: get_jsonp ();"> click me </a> <br/>
<Textarea id = "result" Cols = "50" rows = "3"> </textarea>
</Body>
</Html>
The getjson () method in jquery can be found in: http://www.w3school.com.cn/jquery/ajax_getjson.asp