Cross-domain request for jquery Ajax JSONP use

Source: Internet
Author: User
Tags vars domain server

Transferred from:

The day before yesterday in the project to write an AJAX JSONP use, there is a problem: you can successfully obtain the results of the request, but did not execute the success method, directly executed the error method prompt errors--ajax Jsonp not used before, it is understood to be similar to ordinary AJAX requests, Without deep understanding, this error has occurred, after debugging (check the background code and JS part of the property settings) or not, let me feel very unexpected and puzzled. So, decided to carefully study the use of Ajax Jsonp, and will be the final test of successful learning experience and share under!

First, post the code that can be executed successfully:

(Page section)

1 <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http:// ">
2 3 4 <title>untitled page</title>
5 <script type= "Text/javascript" src= "Http://" ></ Script>
6 <script type= "Text/javascript" >
7 JQuery (document). Ready (function () {
8 $.ajax ({
9 Type: "Get",
Ten Async:false,
URL: "Ajax.ashx",
DataType: "Jsonp",
JSONP: "Callbackparam",//pass to the request handler or page, to obtain the name of the JSONP callback function name (default: Callback)
Jsonpcallback: "Success_jsonpcallback",//Custom JSONP callback function name, default to jquery automatically generated random function name
Success:function (JSON) {
alert (JSON);
alert (json[0].name);
Error:function () {
Alert (' fail ');
a= var "FirstName Brett";
alert (a);

(Handler section)

1 <%@ webhandler language= "C #" class= "Ajax"%>

3 using System;
4 using System.Web;

6 public class Ajax:ihttphandler {
8 Public void ProcessRequest (HttpContext context) {
9 context. Response.ContentType = "Text/plain";
Ten string callbackfunname = context. request["Callbackparam"];
One context. Response.Write (Callbackfunname + "([{name:\" john\ "}])");
-- }
Public bool IsReusable {
get {
return false;
+ }
(+ }


(Request grab Bag)

Ajax Request Parameter Description:


Expected data type returned by the server. If not specified, JQuery is automatically judged intelligently based on the HTTP packet mime information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server is then parsed against this value and passed to the callback function. Available values:

"XML": Returns an XML document that can be processed with jQuery.

HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.

"Script": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. "Note:" On a remote request (not in the same domain), all post requests are converted to get requests. (because the script tag of the DOM will be used to load)

"JSON": Returns the JSON data.

"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.

"Text": Returns a plain text string


Overrides the name of the callback function in a JSONP request. This value is used instead of "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes the "onjsonpload=?" passed to the server.


Specifies a callback function name for the JSONP request. This value will be used instead of the random function name generated by jquery automatically. This is primarily used to create a unique function name for jquery, which makes it easier to manage requests and provides a convenient way to provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache a GET request.

The main difference between Ajax Jsonp and ordinary Ajax requests is the processing of request response results. as shown in the preceding code, the result is:

 success_jsonpCallback([ { name:"John"} ] ); ————其实就是,调用jsonp回调函数success_jsonpCallback,并将要响应的字符串或json传入此方法(作为参数值),其底层的实现,大概的猜想应该是:
 function success_jsonpCallback(data)

经测试,ajax jsonp对同步或异步请求没有影响。


Asynchronous JavaScript and XML (Ajax ) are key technologies that drive a new generation of Web sites (popular terminology for Web 2.0 sites). Ajax allows data retrieval in the background without disturbing the display and behavior of the WEB application. Using XMLHttpRequest functions to get data, it is an API that allows client-side JavaScript to connect to a remote server via HTTP. Ajax is also a driving force for many mashups, which can make content collections from multiple locations a single WEB application.

However, because of browser restrictions, this method does not allow cross-domain communication. If you try to request data from a different domain, a security error occurs. These security errors can be avoided if you have control over the remote server where the data resides and each request goes to the same domain. But what is the use of WEB applications if you only stay on your own servers? What if you need to collect data from multiple third-party servers?

Understanding the same-origin policy limitations

The same-origin policy prevents scripts loaded from one domain from getting or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is very old and exists from Netscape Navigator version 2.0.

A relatively simple way to overcome this limitation is to have the Web page request data to the Web server it originates from, and have the Web server forward requests to a true third-party server like a proxy. Although the technology has been widely used, it is not scalable. Another way is to use frame features to create a new zone in the current Web page, and use the GET request to get any third-party resources. However, when resources are obtained, the content in the framework is limited by the same-origin policy.

The best way to overcome this limitation is to insert a dynamic script element into a Web page that points to a service URL in another domain and gets the data in its own script. It starts executing when the script loads. This approach is possible because the same-origin policy does not prevent dynamic script insertions and considers the script to be loaded from the domain that provides the Web page. However, if the script tries to load a document from another domain, it will not succeed. Fortunately, this technique can be improved by adding JavaScript Object Notation (JSON).

1. What is JSONP?

To understand JSONP, you have to mention JSON, so what is JSON?

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

2. What is the use of JSONP?

Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then output JSON data on the server and execute callback functions to resolve cross-domain data requests.

3, how to use JSONP?

The demo below is actually a simple representation of JSONP, after the client declares the callback function, the client requests data across the domain through the script tag, then the server returns the corresponding data and executes the callback function dynamically.

HTML code (either):

HTML code
  1. <Meta content="text/html; Charset=utf-8 " http-equiv="content-type " />
  2. <script type="Text/javascript">
  3. function Jsonpcallback (Result) {
  4. alert (result);
  5. for (var i in result) {
  6. Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
  7. }
  8. }
  9. var jsonp=document.createelement ("script");
  10. jsonp.type="Text/javascript";
  11. jsonp.src="Http://";
  12. document.getElementsByTagName ("Head") [0].appendchild (JSONP);
  13. </Script>


HTML code
  1. <Meta content="text/html; Charset=utf-8 " http-equiv="content-type " />
  2. <script type="Text/javascript">
  3. function Jsonpcallback (Result) {
  4. alert (RESULT.A);
  5. alert (result.b);
  6. alert (RESULT.C);
  7. for (var i in result) {
  8. Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
  9. }
  10. }
  11. </Script>
  12. <script type="Text/javascript" src= " Jsonpcallback "></script>

JavaScript links must be under function.

Server PHP Code (services.php):

PHP code
  1. <?php
  2. The service side returns JSON data
  3. $arr =Array (' A ' =>1,' B ' =>2,' C ' =>3,' d ' =>4,' e ' =>5);
  4. $result =json_encode ($arr);
  5. Echo $_get[' callback ']. ' ("hello,world!") ';
  6. Echo $_get[' callback ']. " ($result) ";
  7. Dynamic Execution callback function
  8. $callback =$_get[' callback ');
  9. Echo $callback."  ($result) ";

If the above JS client code is implemented in jquery, it is also very simple.


How to implement the client JS code in jquery 1:

JS Code
  1. <script type="Text/javascript" src="jquery.js" ></script>
  2. <script type="Text/javascript" >
  3. $.getjson ("",
  4. function (Result) {
  5. For (var i in result) {
  6. Alert (i+":" +result[i]);   Loop output a:1,b:2,etc.
  7. }
  8. });
  9. </script>

How to implement the client JS code in jquery 2:

JS Code
  1. <script type="Text/javascript" src="jquery.js" ></script>
  2. <script type="Text/javascript" >
  3. $.ajax ({
  4. URL:"",
  5. DataType:' Jsonp ',
  6. Data:",
  7. JSONP:' callback ',
  8. Success:function (Result) {
  9. For (var i in result) {
  10. Alert (i+":" +result[i]);   Loop output a:1,b:2,etc.
  11. }
  12. },
  13. timeout:3000
  14. });
  15. </script>

How to implement the client JS code in jquery 3:

JS Code
    1. <script type="Text/javascript" src="jquery.js" ></script>
    2. <script type="Text/javascript" >
    3. $.get (' ', {name:encodeuricomponent (' tester ')},   function (JSON) { for (var i in JSON) alert (i+":" +json[i]);}, ' Jsonp ');
    4. </script>

Where Jsoncallback is a function that is registered by the client and gets the JSON data on the cross-domain server after the callback.
This URL is a cross-domain server to take JSON data interface, the parameter is the name of the callback function, the return format is

JS Code
    1. Jsonpcallback ({msg:' This is JSON data '})

Jsonp principle:
First register a callback with the client and then pass the callback name to the server.

At this point, the server becomes JSON data.
Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

The advantage of using JSON is that:

    • It's a lot lighter than XML, and it's not that much redundant stuff.
    • JSON is also very readable, but usually the return is compressed. Unlike a browser like XML can be directly displayed, the browser for the format of JSON display will need to use some plug-ins.
    • Working with JSON in JavaScript is simple.
    • Other languages such as PHP support for JSON is also good.

JSON also has some disadvantages:

    • JSON support in the service-side language is not as extensive as XML, but it a library of many languages.
    • If you use eval () to parse, you are prone to security issues.

However, the advantages of JSON are obvious. He is an ideal data format for AJAX data interactions.

Main tips:

JSONP is a powerful technology for building mashups, but unfortunately it is not a panacea for all cross-domain communication needs. It has some drawbacks that must be carefully considered before submitting development resources.

First, and most important, there is no error handling on the JSONP call. If the dynamic script insert is valid, the call is executed, and if it is not valid, the silence fails. There is no hint of failure. For example, you cannot catch a 404 error from the server, and you cannot cancel or restart the request. However, waiting for a period of time has not responded, do not have to ignore it. (The future JQuery version may have the feature to terminate the JSONP request.)

Another major drawback of JSONP is the danger of being used by untrusted services. Because the JSONP service returns a JSON response packaged in a function call, the function call is executed by the browser, which makes the host WEB application more susceptible to various types of attacks. If you intend to use the JSONP service, it is important to understand the threats it can pose.


Cross-domain request for jquery Ajax JSONP use

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