检查来自jquery $ .get()的响应代码

时间:2014-05-06 06:04:25

标签: jquery ajax

我知道这可以用ajax完成,但我想知道如何使用get()快捷方式来完成...

鉴于此:

$.get('someurl.com', function(data, statusText, xhr) {
        $('#sometag').html(data);
    });

我怎么能对任何不是200的东西进行错误检查?如果请求有效但没有有用的数据要返回,我正在访问的api会定期返回204。

2 个答案:

答案 0 :(得分:1)

小提琴链接 - http://jsfiddle.net/smegha11/6xu3K/

您可以使用xhr.status属性检查响应代码

$.get('someurl.com', function(data, statusText, xhr) {
    if(xhr.status==200)
    {
       $('#sometag').html(data);
    }
});

答案 1 :(得分:-1)

使用回调方法

The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain 
multiple .done(), .fail(), and .always() callbacks on a single request.

示例

$.get( "someurl.com", function() {
  Console.log( "success" );
}).done(function() {
    Console.log( "second success" );
  }).fail(function() {
    Console.log( "error" );
  }).always(function() {
    Console.log( "finished" );
  });

检查 $get

的文档

以下是每个功能正在接收的参数

jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

jqXHR objects

的文档