Jsonp has been used for recent work. record it.
Jsonp
The simple principle is to use the <SCRIPT> tag to introduce a JS that defines JSON data, because the <SCRIPT> tag is not restricted by the domain name.
Example
<SCRIPT type = text/JavaScript>
Function callback (jsondata)
{
Alert (jsondata. username );
}
</SCRIPT>
<SCRIPT type = text/JavaScript>
Callback ({"username": "test", "Age": 11 });
</SCRIPT>
This should be understandable.
Callback ({"username": "test", "Age": 11 });
Save it as a JS file and place it anywhere. Then introduce this JS file directly here, which can also be executed.
Jquery has encapsulated this process and directly calls it to obtain JSON data.
Calls in MVC
First define a jsonpresult,
Public class jsonpresult <t>: actionresult {public t OBJ {Get; set;} Public String callbackname {Get; set;} public jsonpresult (t obj, string callback) {This. OBJ = OBJ; this. callbackname = callback;} public override void executeresult (controllercontext context) {var JS = new system. web. script. serialization. javascriptserializer (); var jsonp = This. callbackname + "(" + Js. serialize (this. OBJ) + ")"; context. httpcontext. response. contenttype = "application/JSON"; context. httpcontext. response. write (jsonp );}}
Action writing
Public actionresult getjsonp (string callback) {If (string. isnullorempty (callback) callback = "Callback"; user u = new user (); // generate the U object return New jsonpresult <in1_user> (u, callback );}
Action returns a JSCode
Callback ({"userid": 45516, "username": "XXX"
})
Jquery call
function getuserinfo (checkuser) {$. ajax ({type: "Get", URL: "http: // xxx/user/getjsonp? Callback =? ", Cache: false, error: function () {}, jsonp:" Callback ", datatype:" jsonp ", success: function (result) {checkuser (result ); // checkuser is a function used to process user objects. }}