Two implementation methods of JSONP in jQuery: jqueryjsonp
The front-end code is as follows:
The background Action code is as follows:
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 customize our own callback function by setting the jsonpCallback parameter for the jsonp request.
The following three lines of code set the JSONP request method:
DataType: "jsonp ",
Jsonp: "jsonpcallback", // specify the callback function. The name can be anything you like, such as callback, but must be consistent with the GET parameter of the next line.
Data: "name = jxq & mail = 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 properties: name and Email, so we can directly call json. name and json. email
Through this article, I hope to help you learn this part. Thank you for your support!