什么是Ajax调用:'成功'还是'失败'?

时间:2012-01-07 21:30:31

标签: jquery ajax

这似乎是101级,但我找不到答案! (相反,我找到了成功或失败的方法,jQuery的ajax().success等等。

我的预感是:

  • success:200 HTTP返回码
  • failure:其他任何内容。

2 个答案:

答案 0 :(得分:7)

这不是真正的AJAX,而是jQuery问题,因为成功回调只是jQuery的特征,而不是整个AJAX。

从jQuery源代码中,您可以看到它是如何实现的

// If successful, handle type chaining
            if ( status >= 200 && status < 300 || status === 304 ) {

                // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
                if ( s.ifModified ) {

                    if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
                        jQuery.lastModified[ ifModifiedKey ] = lastModified;
                    }
                    if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
                        jQuery.etag[ ifModifiedKey ] = etag;
                    }
                }

                // If not modified
                if ( status === 304 ) {

                    statusText = "notmodified";
                    isSuccess = true;

...
else fail with the error callback

因此,基本上,如果HTTP响应代码介于200和299之间(包括)或304,那么它将用于success回调,否则,它将是error回调。

答案 1 :(得分:1)

ajax调用返回4个不同的readystates中的1个(4是接收数据的重要一个)

以及状态,可以是任何正常的响应状态(200都没有错误)

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

一个有用的例子:

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

相关问题