Cross-domain request for jquery Ajax JSONP use

Source: Internet
Author: User


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://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">234<title>untitled page</title>5<script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></ Script>6<script type= "Text/javascript" >7JQuery (document). Ready (function(){8$.ajax ({9Type: "Get",TenAsyncfalse, OneURL: "Ajax.ashx", ADataType: "Jsonp", -JSONP: "Callbackparam",//The parameter name passed to the request handler or page to obtain the name of the JSONP callback function (default: Callback) -Jsonpcallback: "Success_jsonpcallback",//Custom JSONP callback function name, default to jquery auto-generated random function name theSuccess:function(JSON) { -alert (JSON); -alert (json[0].name); -}, +Errorfunction(){ -Alert (' fail '); +} A}); at         varA= "FirstName Brett"; -alert (a); -}); -</script> - -<body> in</body> -


(Handler section)

1<%@ WebHandler language= "C #" class= "Ajax"%>2 3Using System;4Using System.Web;5 6public class Ajax:ihttphandler {7     8PublicvoidProcessRequest (HttpContext context) {9Context. Response.ContentType = "Text/plain";TenString callbackfunname = context. request["Callbackparam"]; OneContext. Response.Write (Callbackfunname + "([{name:\" john\ "}])"); A} -   -public bool IsReusable { theget { -             return false; -} -} +  -}

(Request grab Bag)

Ajax Request Parameter Description:

DataTypeString

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

JsonpString

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.

JsonpcallbackString

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)        {            success(data);        }
 经测试,ajax 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.