This is the case with jQuery's jsonp cross-origin. jqueryjsonp cross-Origin

Source: Internet
Author: User

This is the case with jQuery's jsonp cross-origin. jqueryjsonp cross-Origin

Cross-origin requests include the src attribute in iframe, img, and script.
So how does jquery solve cross-origin requests?

I:
The project jsonp2 contains an app. js file. The Code is as follows:

function app(json){    alert(json['name']);}

Index.html in project jsonp1

<script type="text/javascript" src="http://127.0.0.1:8020/jsonp2/js/app.js"></script><script type="text/javascript">    app({'name':"guoyansi",'age':25});</script>

Execution result:
The app method is not stated here. How can it be called?
The first script has a cross-origin request. src points to app. js in jsonp2.
In app. js, the app method is declared.
Now let's look at the source code of index.html in Firefox and open the script of app. js.

Conclusion: The app. js introduced from the outside will eventually be loaded into the browser and rendered as follows:

<script type="text/javascript">    function app(json){    alert(json['name']);}</script>

According to the above conclusion
If we use the script to send a request to the background across domains,
We return a piece of js Code at the backend. Can the front-end be called?
Now let's verify the hypothesis.
We use java as an example:
Create a javaweb project and create a servlet,
This servlet returns a js Code;

Package servelt; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class Jsonp2 extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/javascript; charset = UTF-8"); // jsonp actually writes back javascript code. // or: response. setContentType ("text/plain; charset = UTF-8"); PrintWriter out = response. getWriter (); out. print ("app ({'name': 'siss', 'age': '25'})"); out. flush (); out. close ();} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

Create another project and create an index.html page

<!DOCTYPE html>

The second script above directly executes the servlet on this new project.
Finally, it is parsed by the browser into the following format:

<Script type = "text/javascript"> app ({'name': 'siss', 'age': '25'}) </script>

The final page of index.html looks like this:

<! DOCTYPE html> 

I think everyone knows how to execute the above Code.
The method call of the js Code returned by the above Code is always written to the server. We can also specify the reverse call name to be returned from the client.
Modify servlet:

Package servelt; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class Jsonp2 extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/javascript; charset = UTF-8"); // jsonp actually writes back a piece of javascript code String appMethod = request. getParameter ("appMethod"); PrintWriter out = response. getWriter (); out. print (appMethod + "({'name': 'siss', 'age': '25'})"); out. flush (); out. close ();} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

On the client side, specify the JSS to be returned by the server, and modify index.html.

<!DOCTYPE html>

In the above example, a piece of executable js Code is returned to call the local method.
We encapsulate the above example. The java code remains unchanged.

(Function ($) {$. gys = function (opt) {var scriptCode = (new Date ()). getTime (); // concatenate the script tag var html = "<"; html + = "script id = 'script" + scriptCode + "'Type = 'text/javascript 'src = '" + opt. src + "? "+ Opt. callbackName + "=" + opt. callback + "'>"; html + = "<"; html + "/script>"; // declare a global method variable for calling the js method returned remotely, the method name has callback to specify window [opt. callback] = function (json) {opt. success (json); // Method for calling the current parameter $ ("# script" + scriptCode ). remove (); // Delete the script tag} $ ("head "). append (html); // insert script tag}) (jQuery );

Call:

$(function(){    $.gys({        callbackName:"appMethod",        callback:"app",        src:"http://192.168.6.130:8080/jp/Jsonp2",        success:function(data){            console.log(data);        }    });                });

Do you think this is a bit like jquery's jsonp.
Let's take a look at jquery's jsonp.
Jsonp uses the above principle.

Let's take a look at jquery's jsonp usage.

$. Ajax ({type: "get", // jsonp can only trigger get request url: "" // cross-origin url dataType: "jsonp", jsonp :"", // corresponds to the encapsulated callbackName jsonpCallback: "", // corresponds to the encapsulated callback data :{}, // submit the parameter beforeSend: function () {// jsonp mode this method is not triggered. The reason is that this is no longer an ajax event .}, success: funciton (data) {// Call success}, error: function () {// This Is Not ajax, so this method will not trigger .}});

The integration of jsonp and ajax in jquery is confusing. ajax does not have cross-origin requests,
In addition, the core of jsonp is not the xmlhttprequest of ajax, but the http request of the script (script Injection Behavior ).
In addition, such jsonp does not have post requests.
$. GetJSON () and $. getScript () are both advanced encapsulation of jsonp.

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.