Talk about Ajax (ii)

Source: Internet
Author: User
Tags script tag string format browser cache

Yesterday is not finished, do an understanding today.

The first is to tell by mistake.

First, Ajax common errors

The common mistakes of Ajax, except those enumerated yesterday. There is also the following status code:

405, the request type is wrong, such as the request is post, but you use get, usually this situation is in the SPRINGMVC in the @requestmapping, have used SPRINGMVC experience of the small partners know, @ Requestmapping the default request method is get. If you're not checking for copy-and-paste, the 405 status code will appear when you debug Ajax. Of course, you do not pass the Ajax debugging method, usually will go directly error, and will not appear 405 status code hint. In general, the probability of this problem is very small, because there are postman. Interface testing through postman, in general, if your situation is not correct, the direct prompt does not support the request.

415, the server cannot process the media format that was included with the request. Because you added the contenttype in AJAX and specified the media format as Application/json;

If you do not include @requestbody in your parameter list, it will appear 415.

@RequestBody is typically used to process contenttype content that is not the default Application/x-www-form-urlcode encoding. For example, Application/json and Application/xml, in general, the treatment of Application/json.

For example:

403, this is usually your request parameters and receive parameters inconsistent, such as createdate in the foreground is a string type, but the background you are using the date type to receive, this problem occurs.

In general, when the parameters are more, it is recommended to use the object (more than three parameters, it is recommended to use the object is better).

500, this is usually a problem with the service-side code. This depends on the specific debugging situation to see. such as a null pointer or a type conversion exception, and so on.

Second, how to debug Ajax

For example, I passed postman to test, did not find the problem, does not mean that the web-side asynchronous request no problem. For example, I mentioned in the above Ajax common errors, these common errors, rarely can be found through the postman. Because developers, because of negligence, too lazy to test (unit test) and other possible unexpected causes cause problems. Or maybe I found out through the unit test that it's not a problem, it doesn't mean the web development request URL or the Android request.

Like what:

This code returns the collection data normally without a slash, while the Web request has a slash.

This is because of the string, if you change its return value to object or change its tojsonstring () to Tojson (), you can get normal JSON data instead of string data with slashes.

Although it is said that a slash can be done with the eval of jquery and the Replace method on the Android side, it is best not to go around a large circle.

The means of the mode, mainly in the error function plus the corresponding three parameters XMLHttpRequest, Textstatus, Errorthrown and so on.

Pop-up status code is Xmlhttprequest.status, the normal status code should be 200.

The status code is explained below:

1**: Request received, continue processing
2**: Successful operation received, analysis, acceptance
3**: Completion of this request must be further processed
4**: request contains an error syntax or cannot be completed
5**: The server failed to perform a fully valid request
100--customer must continue to make a request
101--client requires server to convert HTTP protocol version on request
200--Trading Success
201--prompt to know the URL of the new file
202--accepted and processed, but processing not completed
203--return information is indeterminate or incomplete
204--request received, but return information is empty
205--the server has completed the request, the user agent must reset the files that are currently viewed
206--server has completed a partial user's GET request
300--requested resources can be obtained in multiple places
301--Delete request data
302--found the request data at a different address
303--advising customers to access other URLs or access methods
304--client has performed a get, but the file has not changed
The resource requested by 305--must be obtained from the address specified by the server
306--code used in previous versions of HTTP, no longer used in the current version
307--declaring the requested resource temporary deletion
400--error requests, such as syntax errors
401--Request Authorization failed
402--reserved valid Chargeto header response
403--Request not allowed
404--no files, queries, or URLs found
405--the method defined by the user in the Request-line field does not allow
406--request resource is inaccessible based on accept drag sent by user
407--similar to 401, the user must first be authorized on the proxy server
408--client does not complete the request within the user-specified time of starvation
409--the current resource state, the request cannot be completed
This resource is no longer available on the 410--server and has no further reference address
411--server rejects user-defined Content-length property requests
412--one or more request header fields are incorrect in the current request
413--the requested resource is greater than the size allowed by the server
414--The requested resource URL is longer than the length allowed by the server
415--requesting a resource does not support requesting an item format
The 416--request contains a range request header field that does not have a range indication value within the current request resource scope, and the request does not contain a If-range request header field
The 417--server does not meet the expectations specified by the request Expect header field, and if it is a proxy server, the next level of server may not satisfy the request
500--Server generates internal error
501--server does not support the requested function
502--server is temporarily unavailable, sometimes to prevent system overloads
503--server overload or pause repair
504--Gateway overload, Server uses another gateway or service to respond to users, waiting time setting value is longer
505--server does not support or deny the HTTP version specified in the request header

As for xmlhttprequest.readystate, the process of the Ajax asynchronous request server (altogether five processes):

(0) not initialized
This phase confirms that the XMLHttpRequest object is created and is ready for an uninitialized call to the open () method. A value of 0 indicates that the object already exists, or the browser will error--the object does not exist.


(1) Loading
This phase initializes the XMLHttpRequest object by invoking the open () method and setting the object state based on the parameter (method,url,true). and call the Send () method to start sending requests to the server. A value of 1 indicates that a request is being sent to the server.


(2) Loading completed
This stage receives server-side response data. However, only the raw data of the server response is obtained, and it cannot be used directly on the client. A value of 2 indicates that the full-part response data has been received. and prepare for the next phase of data parsing.


(3) Interactive
This phase resolves the received server-side response data. That is, the data is converted into a format that can be accessed through the responsebody, ResponseText, or Responsexml properties based on the MIME type returned by the server-side response header, ready for client invocation. State 3 indicates that the data is being parsed.


(4) Complete
This phase confirms that all data has been resolved to the format available to the client, and the parsing is complete. A value of 4 means that the data is parsed and the data can be obtained from the corresponding properties of the XMLHttpRequest object.
In summary, the life cycle of the entire XMLHttpRequest object should contain the following phases:
Create-Initialize request-Send request-receive data-parse data-complete

Use an example to illustrate:

For example, I call a friend from afar,

First, I have to have a cell phone, no phone how to call, correspondence (0);

Secondly, I will convey to him the first words I have said, which is (1);

Thirdly, what I have said has been communicated to him, which is (2);

Four, he needs to understand what I mean in my words, this is (3);

Five, he has understood the meaning of my words, which is (4);

This example may not be particularly appropriate, but I think it is a good indication of the process of asynchronous request service and the meaning of readystate.

Third, the meaning of the parameters in Ajax ($.ajax in jquery as an example)

1.url:
Requires that the requested address be sent as a parameter of type String (the current page address is assumed to be the default).

2.type:
A parameter of type String is required, and the request method (post or get) defaults to get. Note Other HTTP request methods, such as put and delete, can also be used, but only some browsers support it.

3.timeout:
Requires a parameter of type number to set the request time-out (in milliseconds ). This setting overrides the global setting of the $.ajaxsetup () method.

4.async:
Requires a parameter of type Boolean , which is set to trueby default and all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the synchronization request locks the browser , and the user's other actions must wait for the request to complete before it can be executed.

5.cache:
A parameter that is required to be of type Boolean , which defaults to True (False when datatype is a script), and set to false will not load the request information from the browser cache .

6.data:
Requires data to be sent to the server as an Object or a String of type parameters. If it is not already a string, it is automatically converted to a string format . The GET request will be appended to the URL . To prevent this automatic conversion, you can view the processdata (prevent auto-convert) option. The object must be in key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2. In the case of arrays, jquery automatically corresponds to the same name for different values. For example {foo:["Bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.

7.dataType:
Requires a parameter of type String that expects the data type returned by the server. If not specified , jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter. The following types are available:
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 When you make a remote request (not under the same domain), all post requests are converted to get requests.
JSON: Returns the JSON data.
JSONP:JSONP format. When a function is called using the Sonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function.
Text: Returns a plain text string.

8.beforeSend:
The main purpose of this parameter is to perform some operations before sending a request to the server. Parameters that require a function type can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
This Options parameters passed when calling this Ajax request
}
9.complete:
A parameter that is required to be a function type, called when the request is complete (invoked when the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type.
function (XMLHttpRequest, textstatus) {
This Options parameters passed when calling this Ajax request
}

10.success:

The

Request is a parameter of the Function type, and the callback function called after the request succeeded has two parameters.
         (1) is returned by server and processed data based on the datatype parameter.
         (2) A string that describes the status .
         function (data, textstatus) {
            //data may be xmldoc, jsonobj, HTML, text, and so on
             this; //The options parameter passed when calling this Ajax request
         }

11.error:
The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:
function (XMLHttpRequest, textstatus, Errorthrown) {
Normally textstatus and Errorthrown only one of them contains information
This Options parameters passed when calling this Ajax request
}

12.contentType:
A parameter of type string is required, and when the message is sent to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

13.dataFilter :
requires a function type parameter to preprocess the original data returned by Ajax. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
            function (data, type) {
                //Return to processed data
                 return data;
           }

14.dataFilter:
A function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
function (data, type) {
Returns the processed data
return data;
}

15.global:
Requires a parameter of type Boolean, which is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.

16.ifModified:
A parameter of type Boolean is required, and the default is False. Get new data only when the server data changes. Server data changes are based on the last-modified header information. The default value is False, which ignores header information.

17.jsonp:
Requires a parameter of type string to override the name of the callback function in a JSONP request. This value is used instead of the "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.

18.processData:

Requires a parameter of type Boolean, which is true by default. By default, the data sent is converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.

19.scriptCharset:
A parameter of type string is required and is used to force the character set (charset) only if the request is datatype as "JSONP" or "script" and the type is get. Typically used when local and remote content encodings are different.


The above 1,2,6,7,10,11,12 is more commonly used in my development process. The others are almost seldom used.

Four, SSM framework and Ajax three ways (mainly describes the parameters of transmission and reception)

First, write directly in the argument list.

Advantages, directly indicate the parameter type, to ensure that the front-end and background parameters of the same type, you can receive and processing;

Disadvantage, it is recommended to use the object when there are too many parameters, otherwise the object parameter list may need to be modified as the business changes, resulting in some unnecessary exceptions, such as 415 status code and 403 status code exception or 500 status code exception.

The second, by HttpServletRequest


Third, use map

Note that if you use map, remember to add @requestparam to the parameter list, or you will find that the parameter cannot be transmitted.

All three of these, if used in Ajax asynchronous interactions, can be found by acquiring the key to get the value.

Of course, the essence is based on the HTTP request.

Talk about Ajax (ii)

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.