Examples of jsonp Principles and Applications in MVC

Source: Internet
Author: User

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. }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.