ASP. Application of the Ajax Jsonp of the jquery cross-domain request (reprint)

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)

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head>    <title>Untitled Page</title>     <Scripttype= "Text/javascript"src= "Http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></Script>     <Scripttype= "Text/javascript">jQuery (document). Ready (function() {$.ajax ({type:"Get", Async:true, URL:"ajax.ashx", DataType:"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 nameSuccess:function(JSON) {alert (JSON); Alert (json[0].name); }, Error:function() {alert ('fail');        }        }); vara="firstName Brett";    alert (a);    }); </Script>    </Head> <Body> </Body></HTML>

(Handler section)

<%@ WebHandler language="C #"class="Ajax"%>usingSystem;usingsystem.web; Public classAjax:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain";//Note that it is necessary to declare that the return type of HttpResponse is Text/plain, and that the error method is always taken when calling Jsonp using JQuery's Ajax method, indicating "fail"        stringCallbackfunname = context. request["Callbackparam"]; Context. Response.Write (Callbackfunname+"([{name:\ "john\"}])"); }      Public BOOLisreusable {Get {            return false; }    }}

(Request grab Bag)

Ajax Request Parameter Description:

DataType String

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

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

Jsonpcallback String

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 above code, the response result is: Success_jsonpcallback ([{name: "John"}]); ———— is actually called the JSONP callback function Success_jsonpcallback, and will respond to the string or JSON into this method (as a parameter value), its underlying implementation, presumably the conjecture should be: function Success_  Jsonpcallback (data) {success (data); }

After testing, Ajax Jsonp has no effect on synchronous or asynchronous requests.

Note the HTTP return type of the JSONP handler must be text/plain

In front of us in the Code of the processing program to write the HttpResponse return type must be text/plain, no, the front desk jquery in the call Ajax method Jsonp error, this is why?

The reason for this is that JSONP implements cross-domain AJAX requests by declaring a script tag in the foreground browser page and then setting the SRC attribute of the label to the address of the URL parameter in jquery's Ajax method. The root of this is the use of HTML script tags to cross-domain access to URL address this feature. The script tag requires its SRC address to return the contents of the Content-type must be Text/plain, no, the previous HTML page will be an error. So this requires us to declare that the return type of HttpResponse in the backend handler must be text/plain.

For example, if you use ASP. NET Webapi as Jsonp handler in the background, construct a Httpresponsemessage object that wraps the returned content into Httpresponsemessage, Declaring its mediatype (that is, Content-type) is Text/plain:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Text;usingsystem.web;usingSystem.Web.Http;namespacejsonpserver.controllers{ Public classHelloworldcontroller:apicontroller { Publichttpresponsemessage Get () {httpresponsemessage responsemessage=Request.createresponse (Httpstatuscode.ok); Responsemessage.content=NewStringcontent ("token (' Hello world! ')", Encoding.UTF8,"Text/plain"); returnResponsemessage; }    }}

The HTTP type returned by this webapi will be text/plain.

ASP. Application of the Ajax Jsonp of the jquery cross-domain request (reprint)

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.