Two jsonp implementations in ASP. NET and a simple implementation of other cross-domain solutions

Source: Internet
Author: User

Two jsonp implementation methods in jquery:

It is very simple, so you can directly go to the code!

The front-end code is as follows:

<SCRIPT type = "text/JavaScript"> $ (function () {alert ("start... "); // The first method $. ajax ({type: "Get", URL: "http: // localhost: 9524/home/processcallback", // This is a URL address different from the current domain, here is a simple demonstration, so the same domain datatype: "jsonp", jsonp: "jsonpcallback", // specifies the callback function. Here the name can be anything you like, such as Callback, but it must be consistent with the get parameter of the next line data: "name = jxq & Email = feichexia@yahoo.com.cn & jsonpcallback =? ", // Jsonpcallback is consistent with the preceding jsonp value success: function (JSON) {alert (JSON. name); alert (JSON. email) ;}}); // method 2 $. getjson ("http: // localhost: 9524/home/processcallback? Name = Xiaoqiang & Email = jxqlovejava@gmail.com & jsonpcallback =? ", Function (JSON) {alert (JSON. name); alert (JSON. email) ;}); alert ("end... ") ;}); </SCRIPT>

The background action code is as follows:

public string ProcessCallback(string name, string email){   if (Request.QueryString != null)   {       string jsonpCallback = Request.QueryString["jsonpcallback"];       var user = new User       {            Name = name,            Email = email       };       
       return jsonpCallback + "(" + new JavaScriptSerializer().Serialize(user) + ")";   }   return "error";}

The result is displayed after running. I tracked the background processcallback code, for example:

We can see that the value of jsoncallback is "jquery17104721......", which is sent from the front end to the remote server background for action. Here jquery171 .. it indicates the jquery version, which can be simply understood as the jsonp type request callback function. jquery will generate such a jsonp callback function every time we specify the Ajax request method as jsonp. Although jquery will automatically generate a callback function for us, we can also setJsonpcallbackThe parameter customizes a callback function for the jsonp request.

The following three lines of code set the jsonp request method:

Datatype: "jsonp", jsonp: "jsonpcallback", // specify the callback function. Here the name can be whatever you like, such as Callback, but it must be consistent with the get parameter of the next line data: "name = jxq & Email = feichexia@yahoo.com.cn & jsonpcallback =? ", // Jsonpcallback is consistent with the preceding jsonp Value

The second method is to add jsonpcallback =? directly after the get parameter? .

We can infer that after doing so, jquery's internal mechanism will help us bypass the cross-origin access restriction of the browser, and then we can request cross-origin actions just like normal requests for actions in the same domain.

Finally, a function expression is returned:

return jsonCallback + "(" + new JavaScriptSerializer().Serialize(user) + ")";

The result returned to the front-end is similar to the jquery17104721 .... ('{name: "jxq", email: "feichexia@yahoo.com.cn"}'), it will be executed as soon as it returns to the front end, the result is a javascript object, the object has two attributes: name and email, so we can directly call JSON. name and JSON. email.

Don't forget the parentheses when you return them. Let's not talk about the reason. Let's take a look at the example below:

var response = "{'foo' : 'bar'}";var json = eval(response);  // Invalid labelvar json = eval("(" + response + ")"); // OK

In addition, you can dynamically create scripts and embed IFRAME to implement cross-origin. The simple code for dynamically creating a script is as follows:

$ (Function () {var script = document. createelement ("script"); script. type = "text/JavaScript"; script. src = "http: // otherdomain/script. JS "; // load the script asynchronously. onload = script. onreadystatechange = function () {If (! Script. readystate | script. readystate = 'loaded') {// Add (1, 99) after loading is completed; // directly call functions in cross-origin JS}; document. getelementsbytagname ('head') [0]. appendchild (SCRIPT); // Add (1, 99); // This will cause an error because the script has not been loaded yet}); // script. the JS Code is as follows: function add (a, B) {alert ("add:" + A + "+" + B + "=" + (A + B ));}

Of course, you can also request a JS file containing the JS Code (such as test.js.txt) through jquery's getscriptexample to directly paste the Code:

$. Getscript ("http: // otherdomain/test. JS ", function () {alert (" script loaded and executed. "); // The script will be executed directly after loading });

After loading in this way, you can use functions or variables in cross-origin JS just like using Js in the same domain.

Related Article

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.