JQuery Ajax Usage Details and precautions

Source: Internet
Author: User

If you use get in IE7 or earlier requests, the URL restriction is easily overlooked (up to 2083 characters ). Therefore, if the URL may be too long, POST must be used.
--------------------------------------------------------------------------------
Terminate an Ajax request
To terminate a request, you must call the abort () method of the XMLHttpRequest object.
In jQuery, the returned values of $. get, $. post, $. ajax, $. getJSON, and $. getScript... are all XMLHttpRequest objects.
After abort () is called, the ajax request is immediately stopped, but the success callback function is still executed.
Therefore, in the success callback function, you must first determine whether ajaxGet or data exists before executing the callback function. Copy codeThe Code is as follows: var ajaxGet =$. get (someURL, someData, function (data ){
If (! Data) return true;
// TODO
});
AjaxGet. abort ();

CORS Cross-Origin Resoure Sharing is becoming increasingly important. Various map APIs, Weibo APIs, and so on, website developers do not have to put their own satellites, as long as they can obtain the data based on the interfaces opened by others.
This benefits from the cross-source policy.

JSONP is a cross-source policy solution. The basic principle is to use the browser to allow cross-origin acquisition of script resources (including images), generate a script Tag on the server side, and return it back to the client.

Note that the return from the server is not a JSON string, but callbackName + "(" + JSON_string + ")", that is, JSONP.

This is equivalent to returning a piece of JS Code (the assigned function) to the browser and executing it immediately.
Therefore, in the URL sent by the browser (in the form of GET), you need to pass in the callback function name.
Client:Copy codeThe Code is as follows: function deal (data ){
// TODO
}
Var s = document. createElement ("script ")
// Do not call callback, but it must match the Request. QueryString of the server.
S. src = "http: // 172.20.2.60: 8088/newwebsite/MyHandler. ashx? Callback = func ";
Document. body. appendChild (s)

Server (. Net)Copy codeThe Code is as follows: <% @ WebHandler Language = "C #" Class = "Test" %>
Using System;
Using System. Web;
Public class Test: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
Context. Response. Charset = "UTF-8 ";
Context. Response. ContentType = "text/javascript ";
String callback = context. Request. QueryString ["callback"]; // callback function name
String json = "{'name': 'ray', 'msg ': 'Hello world! '} "; // String in JSON format
String result = string. Format ("{0} ({1})", callback, json );
Context. Response. Write (result );
Context. Response. Flush ();
Context. Response. End ();
}
Public bool IsReusable {
Get {
Return false;
}
}
}

If jQuery is used, the callback function name does not need to be added to the URL, because jQuery is already working for you, and this callback function is success.Copy codeThe Code is as follows: $. ajax ({
Url: "http: // 172.20.2.60: 8088/newwebsite/MyHandler. ashx"
, DataType: "jsonp"
, Success: function (data ){
// TODO
}
});

JSONP is very powerful, but there are two pain points, first, security issues.
In any case, you are dumping data from other people's websites, and the content is still a script! That is to say, if someone else is a bad guy and gives you some malicious code, it will be hard to do.

Of course, this problem generally does not happen. After all, the data that I want to request is either familiar with or official (what Google map APIs, Sina Weibo APIs are clearly not intended for you ).

Another problem is worrying. The browser cannot directly know whether the JSONP request fails. Even with jQuery, error does not work. Even if a try error occurs, the catch cannot be captured.

So for the moment, there is only one imperfect method, that is, to set a time limit. If no data is returned after the time limit is exceeded, an error is determined. It's not perfect because the network speed varies, so you know.
--------------------------------------------------------------------------------
ContentType in jQuery
Original jQuery websiteCopy codeThe Code is as follows: contentType
Default: 'application/x-www-form-urlencoded; charset = UTF-8'
When sending data to the server, use this content type.
Default is "application/x-www-form-urlencoded; charset = UTF-8", which is fine for most cases.
If you explicitly pass in a content-type to $. ajax (),
Then it'll always be sent to the server (even if no data is sent ).
If no charset is specified, data will be transmitted to the server using the server's default charset;
You must decode this appropriately on the server side.

Through this text we can know in jQuery ajax contentType is 'application/x-www-form-urlencoded; charset = UTF-8 'by default, of course this is the latest version of jQuery. Compared with the previous version, it is somewhat changed.

If you want to serialize an object and send it to the background, you can set contentType to 'application/json'

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.