83

ページがステータス コード 401 を返すかどうかを確認したいのですが、可能ですか?

これが私の試みですが、0しか返されません。

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
});
4

8 に答える 8

103

これはjQuery$.ajax()メソッドで可能です

$.ajax(serverUrl, {
   type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
   data: dataToSave,
   statusCode: {
      200: function (response) {
         alert('1');
         AfterSavedAll();
      },
      201: function (response) {
         alert('1');
         AfterSavedAll();
      },
      400: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      },
      404: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      }
   }, success: function () {
      alert('1');
   },
});
于 2012-09-27T17:31:09.247 に答える
73

3 番目の引数は XMLHttpRequest オブジェクトなので、好きなことを行うことができます。

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});
于 2013-08-13T06:15:31.460 に答える
21

エラー コールバックを使用します。

例えば:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

アラート 404

于 2010-06-02T08:17:06.397 に答える
10

$.ajaxメソッドのエラー関数も実装したほうがいいと思います。

error(XMLHttpRequest, textStatus, errorThrown)関数

リクエストが失敗した場合に呼び出される関数。この関数には 3 つの引数が渡されます。XMLHttpRequest オブジェクト、発生したエラーの種類を説明する文字列、およびオプションの例外オブジェクト (発生した場合) です。2 番目の引数 (null 以外) に指定できる値は、"timeout"、"error"、"notmodified"、および "parsererror" です。

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});
于 2010-06-02T08:17:42.833 に答える
9

status codeを使用してサーバーの応答コードを簡単に確認できるこのソリューションを見つけました。

例 :

$.ajax({
type : "POST",
url : "/package/callApi/createUser",
data : JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
success: function (response) {  
    alert("Account created");
},
statusCode: {
    403: function() {
       // Only if your server returns a 403 status code can it come in this block. :-)
        alert("Username already exist");
    }
},
error: function (e) {
    alert("Server error - " + e);
} 
});
于 2015-06-05T09:48:56.403 に答える
6
$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
于 2010-06-02T08:19:39.927 に答える