ページがステータス コード 401 を返すかどうかを確認したいのですが、可能ですか?
これが私の試みですが、0しか返されません。
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
});
ページがステータス コード 401 を返すかどうかを確認したいのですが、可能ですか?
これが私の試みですが、0しか返されません。
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
});
これは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');
},
});
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
});
エラー コールバックを使用します。
例えば:
jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
alert(xhr.status); }
});
アラート 404
$.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);
}
});
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);
}
});
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});