Ajax debugging method under jquery

Source: Internet
Author: User


This article introduces the Ajax debugging method under jquery. Many debugging methods can be used at one point. However, they will be confusing before they can be used;

AJAX can provide users with a richer user experience. Jquery also provides excellent support for Ajax and abstracts the painful differences in Ajax support from various browsers. It not only provides full-featured$. Ajax ()Methods, such$. Get (),$. Getscript (),$. Getjson (),$. Post ()And$ (). Load ()And so on.


First, we use an example to illustrate jquery's Ajax call process,

One feature is to click the confirm payment button to implement the Balance payment function:

1. First, bind the function to be called to the button on the PHP page:

<Input type = "Submit" name = "pay_btn" id = "pay_btn" value = "confirm payment"/>

<SCRIPT type = "text/JavaScript">

$ (Function (){

$ ("# Pay_btn"). BIND ("click", ABC. balancepay );



2. Script:

If $. Post is used:

VaR abc = {

Balancepay:Function(Event ){

Event. preventdefault ();

VaR tThis = $ (event. currenttarget );

VaR form = tThis. Parents ('form ');

VaR url = form. ATTR ('action ');

VaR DATA = 'Code = 15'; // + $ ('# verifycode'). Val ();

VaR jqxhr = $. Post (URL, Data, undefined, 'jsonp ');

Jqxhr. Done (function (datas ){

// Console. Log ('printed on the console '); // #4

$ ("# MSG"). Text ('result: '+ data );



You can also specify the callback function in the $. Post mode:

VaR jqxhr = $. Post (URL, Data, function (data ){

$ ("# MSG"). Text ('result: '+ data );

}, 'Jsonp ');

Use the $. Ajax method:

VaR jqxhr = $. Post (URL, Data, function (data ){

$ ("# MSG"). Text ('result: '+ data );

}, 'Jsonp ');

Use the $. Ajax method:

VaR jqxhr = $. Ajax ({

Type: 'post ',


Data: {code: '15 ′},

Datatype: 'jsonp ',

Sccuess: function (data ){

Alert ('good ');},

Error: function (XMLHttpRequest, textstatus, errorthrown) {// #3 this error function is useful for debugging. If the parsing is incorrect, an error box is displayed.

Alert (XMLHttpRequest. status );

Alert (XMLHttpRequest. readystate );
Alert (textstatus );
// Paser error;


3. server side:

Public Function actioninterpayproc ($ callback)


// Header ("Content-Type: text/JavaScript ");

// Header ('content-type: text/html; charset = UTF-8 ′);

$ Code = $ _ post ['code'];

// $ Code // #1 A syntax error expression is provided here.

// Echo $ code; // #2 mark it here for subsequent debugging instructions;


$ Result = 1;

// Echo $ _ post ['callback']. '('. json_encode ($ result ). ');'; // note that the encoding method must be consistent with the client request;

Exit (0 );



Debugging tools

Firefox has powerful firebug plug-ins. Currently, newer browsers such as chrome and Safari, and IE 8 have built-in debugging tools. With these debugging tools, you can view the Ajax Execution Process in great detail (the shortcut key for calling the debugging tool in chrome and Firefox is Ctrl + Shift + C );

Firebug is used below;

Debugging method

1. Use firebug to view the callback:

The Ajax method is implemented on the server side asynchronously.ProgramIf an error occurs on the server side and is not displayed on the page, you need to use the debugging tool to view the error. For example, remove the comment in #2 in the preceding example and trigger an Ajax request, you can view the returned error results in the console panel:

If an error occurs in the server program, you can see that the cause of the error is the same as that on a common page, but it is displayed on the Panel returned by Ajax (no display is displayed on the web browser page ).

It should be noted that, if the server uses echo and other methods to print out the variables to be viewed, the Ajax call results must fail, because the name of the callback function appears to be changed, it cannot be parsed;

For example, if the printed variable is 333, the final callback result is: 333 ajaxcallbak (1). The client cannot parse the function name 333ajaxcallbak.

2. Use the error function to print the error message:

$. Ajax () has an error parameter. You can specify a function. This method is called when a request fails. The information provided here is very useful for debugging;

Error: function (XMLHttpRequest, textstatus, errorthrown)

The first parameter XMLHttpRequest returned by the error event has some useful information:

XMLHttpRequest. readystate:

The returned Status Code corresponds to an error description:

Status Code

0-(not initialized) The send () method has not been called

1-(load) The send () method has been called and a request is being sent.

2-(Loading completed) The send () method is executed completely and all response content has been received

3-(interaction) parse the response content

4-(complete) The response content has been parsed and can be called on the client

XMLHttpRequest. Status:

The returned status code is the HTTP status we see on a daily basis. For example, 404 indicates that no page is found;

(For details about the status code, see the appendix ;)


"Timeout", "error", "notmodified", and "parsererror ".

(Default: automatically determines (XML or HTML) The call time when the request fails. There are three parameters: XMLHTTPRequest object, error message, and (optional) captured error object. If an error occurs, in addition to null, the error message (the second parameter) may also be "timeout", "error", "notmodified", and "parsererror ".

Through this error function, the program can easily troubleshoot errors;

For example, in section #2 above, removing comments is equivalent to changing the callback function name. In erro, parsererror is reported;

3. Use console. log to print the output: (Alert)

This is only an auxiliary method to enhance the debugging experience. We can print the tracking of interest variables in JS using the Alert () method, but the pop-up box is frequently annoying. Console. log is an alternative method. It is a method of the firebug plug-in. The result of variables printed by console. log is displayed in the console panel of firebug;

Possible error causes:

1. If the returned results are incorrectly formatted, you can see the results in firebug;

2. For JSON requests, the format is strict:

If the following error is reported through the error function: parsererror

The possible cause is the script encoding problem on the server. You can add the corresponding header information to the first line processed by the server processing function:

Eg: Header ('content-type: text/html; charset = UTF-8 ');

Of course, the most likely reason is that the format is incorrect:

Echo "{'Re': 'success'}"; jquery cannot parse

Echo "{\" re \ ": \" Success \ "}"; no error

Do not output a string in the weird JSON format, or jq1.4 + does not execute the success callback. For example, {ABC: 1} or {'abc': 1} must be output.
{"ABC": 1}

{'Success ': true} to {"success": true}

Related books:

If you are new to jquery, you can read this book. The introduction is comprehensive and easy to understand:

《Sharp jquery"




XMLHttpRequest. Status Code

1xx-Information prompt

These statuses Code Indicates a temporary response. Before receiving a regular response, the client should be prepared to receive one or more 1xx responses.
101-switch protocol.

This type of Status Code indicates that the server successfully accepts client requests.
200-OK. The client request is successful.

203-non-authoritative information.
204-NO content.
205-Reset content.
206-part of content.

The client browser must perform more operations to implement the request. For example, the browser may have to request different pages on the server or repeat the request through the proxy server.

301-the object has been permanently removed, I .e., permanent redirection.
302-the object has been temporarily moved.
304-not modified.
307-temporary redirection.

4xx-client Error
The client seems to be faulty when an error occurs. For example, the client does not provide valid authentication information for a page that does not exist in a request. 400-Incorrect request.

401-Access denied. IIS defines many different 401 errors, which indicate more specific error causes. These specific error codes are displayed in the browser but not in the IIS log:

401.1-Logon Failed.
401.2-login failed due to server configuration.
401.3-the ACL is not authorized due to resource restrictions.

401.4-filter authorization failed.
401.5-An error occurred while authorizing the ISAPI/cgi application.

401.7-the access is rejected by the URL Authorization Policy on the Web server. This error code is dedicated to iis6.0.

403-Access prohibited: IIS defines many different 403 errors, which indicate more specific error causes:
403.1-the execution access is forbidden.

403.2-Read access is forbidden.
403.3-write access is forbidden.
403.4-require SSL.
403.5-ssl128 is required.

403.6-the IP address is rejected.
403.7-client certificate required.
403.8-site access is denied.
403.9-too many users.

403.10-the configuration is invalid.
403.11-change the password.
403.12-access to the ing table is denied.
403.13-the client certificate is revoked.

403.14-reject the directory list.
403.15-the access permission of the client is exceeded.
403.16-the client certificate is untrusted or invalid.

403.17-the client certificate has expired or has not yet taken effect.
403.18-the requested URL cannot be executed in the current application pool. This error code is dedicated to iis6.0.

403.19-CGI cannot be executed for clients in this application pool. This error code is dedicated to iis6.0.

403.20-logon to passport failed. This error code is dedicated to iis6.0.
404-not found.
404.0-(none)-No file or directory found.

404.1-unable to access the web site on the requested port.
404.2-the Web service extended locking policy blocks this request.

404.3-the mime ing policy blocks this request.
405-HTTP predicates used to access this page are not allowed (methods are not allowed)

406-the client browser does not accept the MIME type of the requested page.
407-proxy authentication is required.
412-precondition failed.

413-The Request Entity is too large.
414-the request URI is too long.
415-unsupported media type.
416-the requested range cannot be met.

417-execution failed.
423-locking error.
5xx-Server Error
The server cannot complete the request because of an error.

500-internal server error.
500.12-the application is busy restarting on the Web server.
500.13-the Web server is too busy.

500.15-Direct Request to global. ASA is not allowed.
The 500.16-unc authorization credential is incorrect. This error code is dedicated to iis6.0.

500.18-the URL-authorized storage cannot be opened. This error code is dedicated to iis6.0.
500.100-Internal ASP error.

501-the header value specifies the unimplemented configuration.
502-the Web server received an invalid response when used as a gateway or proxy server.
502.1-CGI application timeout.

502.2-CGI application error. Application.
503-the service is unavailable. This error code is dedicated to iis6.0.
504-gateway timeout.

The 505-http version is not supported.
1xx-Affirmative preliminary reply

These status codes indicate that an operation has started successfully, but the client wants to receive another response before continuing to operate the new command.
110 restart mark the reply.

120 the service is ready and starts in NNN minutes.
125 the data connection is enabled and transmission is starting.
150 the file is in normal state and you are ready to open the data connection.

2XX-a positive response
An operation has been completed successfully. The client can execute new commands. 200 command OK.
202 if no command is executed, there are too many commands on the site.

211 system status or system help reply.
212 directory status.
213 File status.
214 help message.

215name: system type. name indicates the formal system name listed in assignednumbers.
220 the service is ready to execute new user requests.

221 close the control connection. If appropriate, log out.
225 the data connection is opened and there is no transmission in progress.

226 close the data connection. The requested file operation has been successful (for example, transferring a file or dropping a file ).
227 enter the passive mode (H1, H2, H3, H4, P1, P2 ).

230 The user has logged on and continues.
250 the requested file operation is correct and has been completed.
257 "pathname" has been created ".
3xx-Affirmative intermediate reply

The command is successful, but the server needs more information from the client to process the request. 331 the user name is correct and the password is required.
332 You need to log on to the account.

350 the requested file operation is waiting for further information.
4xx-completion of transient Negation

The command fails, but the error is temporary. If the client retries the command, it may be executed successfully. 421 the service is unavailable and the control connection is being closed. If the Service determines that it must be disabled, this response will be sent to any command.

425 data connection cannot be enabled.
426 connectionclosed; transferaborted.

450 file operations not requested. The file is unavailable (for example, the file is busy ).
451 request operation exception termination: processing local error.

452 the requested operation is not performed. Insufficient system storage space.
5xx-permanent completion reply

The command fails. The error is permanent. If the client retries the command, the same error will occur again. 500 syntax error. The command cannot be identified. This may include errors such as too long command lines.

501 syntax error in the parameter.
502 the command is not executed.
503 error command sequence.
504 the command for this parameter is not executed.
530 not logged on.

532 accounts are required to store files.
550 the requested operation is not performed. File is unavailable (for example, the file is not found and no access permission is available ).

551 exceptional request termination: Unknown page type.
552 the requested file operation ended abnormally: exceeds Storage Allocation (for the current directory or dataset ).

553 the requested operation is not performed. The file name is not allowed.
Common FTP status code and Its Causes

150-ftp uses two ports: 21 for sending commands and 20 for sending data. Status Code 150 indicates that the server is preparing to open a new connection on Port 20 and send some data.

226-the command opens a data connection on Port 20 to perform operations, such as file transfer. This operation is successfully completed and the data connection is closed.

230-the status code is displayed after the client sends the correct password. It indicates that the user has successfully logged on.

331-the status code is displayed after the client sends the user name. This status code is displayed no matter whether the user name is a valid account in the system.

426-the command opens the data connection to perform the operation, but the operation has been canceled and the data connection has been closed.

530-the status code indicates that the user cannot log on because the combination of the user name and password is invalid. If you log on with a user account, you may enter the wrong user name or password, or you may choose to allow anonymous access only. If you log on with an anonymous account, the IIS configuration may reject anonymous access.

550-the command is not executed because the specified file is unavailable. For example, the file to get does not exist, or you try to put the file to a directory without the write permission.





Posted by: Large CC |
Oct23, 2012


Weibo:Sina Weibo

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.