Cross-Domain solution two: using JSONP to implement cross-domain

Source: Internet
Author: User

There are many ways to implement cross-domain, except for the cors mentioned in the previous article, there are Jsonp, HTML5, Flash, IFRAME, XHR2 and so on.

This article explores Jsonp's cross-domain principles and records my experience here and shares with you.

The exploration of Jsonp cross-domain principle

We know that when sending HTTP requests using the XMLHttpRequest object, we encounter the same-origin policy issue, and domain requests are blocked by the browser.

Is there a way to bypass the XMLHttpRequest object for HTTP cross-domain requests?

In other words, is it possible to send cross-domain HTTP requests without using the XMLHttpRequest object?

Careful you may find, like:

<script type= "Text/javascript" src= "Http://www.a.com/scripts/1.js" ></script>

<link rel= "stylesheet" href= "Http://www.c.com/assets/css/1.css"/>

This tag is not subject to "cross-domain" issues, strictly speaking, this is not a cross-domain, which refers to sending HTTP requests to non-homologous domains in script code, which is only a cross-site resource request.

So, can we use cross-site resource requests as a way to implement cross-domain HTTP requests?

Take the <script></script> tag as an example to explore, first look at a section of code:

<! DOCTYPE html>

In this code, there are 2 JavaScript fragments, the 1th fragment defines a processing function handler (), the processing function is relatively simple, do not do any processing of the data, just put it alert out, the 2nd fragment called it, run this page browser will pop up " Success ".

We assume that the 2nd JavaScript fragment is stored elsewhere, and then we use the <script src= ""/> to bring it in, like this:

<! DOCTYPE html>

Service.a.com/script/1.js:

Handler (' success ');

This method is equivalent to writing the JavaScript code directly on the page, but what can we associate with this?

Whether we can define the handler on this page beforehand, the service side returns the JS script, the content of the script is the callback to the handler, the data returned by the service is passed back in the form of the parameter:

Handler (' data returned by the service ');

Then "Forge" HTTP requests by dynamically adding <script src= "service address" ></script> nodes to the head node of the current page?

As a result, you can write a simple test case:

Write the server first, a very simple service, return the string "Hello World", General handler Service.ashx:

Using system;using system.collections.generic;using system.linq;using system.web;namespace JSONPDemo.Service{    / <summary>///    Service2 Summary description///    </summary> public    class Service2:ihttphandler    {        public void ProcessRequest (HttpContext context)        {            context. Response.ContentType = "Text/plain";            Context. Response.Write ("Handler (' Hello World ');        }        public bool IsReusable        {            get            {                return false;    }}}

Then write the client, a simple static Web page, index.html:

<! DOCTYPE html>

Test success!

In this test example, we used a generic handler to write a simple service that returned Hello World, and then implemented the cross-domain HTTP request in a dynamically created <script></script> node way.

Because the <script>, tag resource requests are asynchronous, we implement a cross-domain asynchronous HTTP request.

But this is not enough, a page may have multiple HTTP requests, and the handler for the example above has only one--handler.

Different requests should be handled by different handlers, and the above code will be modified slightly, just add a parameter to the URL in the src attribute of the <script> tag to specify the name of the callback function:

Service side:

        public void ProcessRequest (HttpContext context)        {            context. Response.ContentType = "Text/plain";            The frontend specifies the name of the callback function            var callbackfuncname = context. Request.querystring["Callback"];            var responsedata = "Hello World";            Callback script, such as: Handler (' ResponseData ');            var scriptcontent = string. Format ("{0} (' {1} ');", Callbackfuncname, responsedata);            Context. Response.Write (scriptcontent);        }

Web client:

<! DOCTYPE html>
Jsonp across domains using jquery

jquery's ajax approach encapsulates JSONP-type cross-domain, and if you use jquery for Jsonp cross-domain HTTP requests, it becomes very simple:

<! DOCTYPE html>

Just setting datatype to "JSONP" makes cross-domain requests, as simple as sending non-cross-domain requests.

jquery encapsulates the callback function for us, generally do not need us to write, if you do not want to handle in success, want to write the processing function alone, then you can set these 2 parameters to achieve:

    • JSONP: "Callback",//The callback function name parameter passed to the server, if not set, the default is "callback"
    • Jsonpcallback: "Handler",//The callback function name passed to the server, if not set, the default is the shape "jquery111007837897759742043_1460657212499" The name of the function automatically generated by jquery

It is important to emphasize that:

1.JSONP Although it looks like a general Ajax request, but its principle is different, JSONP is the first section of the article on the principle of encapsulation, is through the dynamic loading of <script> tags to achieve cross-domain requests, And the general Ajax request is through the XMLHttpRequest object;

2.JSONP is not a standard protocol, its security and stability are inferior to the recommended CORS;

3.JSONP does not support post requests, even if the request type is set to post, it is still essentially a GET request.

Demo Download (1507)

Cross-domain solution rollup in javascript:

Cross-domain Solution one: using Cors for cross-domain

Cross-Domain solution two: using JSONP to implement cross-domain



Cross-Domain solution two: Implementing Cross-domain using JSONP

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.