2017-05-22 13 views
1

私のAJAXリクエストからHTTPレスポンスコード/レスポンスヘッダを取得しようとしています。AJAXリクエスト - 正常なリクエストのためにHTTPコード/レスポンスヘッダを取得する

$("#callContact1").click(function() { 
 
    $.ajax({ 
 
     url: "https://www.server.com?type=makecall", 
 
     data: {}, 
 
     type: "GET" 
 
    }) 
 
    .then(function(data) { 
 
     $('#ajaxResponse').html(data).show(); 
 
    }) 
 
    .fail(function(xhr) { 
 
     var httpStatus = (xhr.status); 
 
     var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus; 
 
     console.log('ajaxError: ' + ajaxError); 
 
     //make alert visible 
 
     $('#ajaxResponse').html(ajaxError).show(); 
 
    }) 
 
})

正常に動作している:ここでは私のオリジナルのスクリプトです。私はこれを試してHTTPレスポンスコード/ヘッダーを取得し、console.logでこれを表示するように更新しましたが、そこに何も表示されません。ここに私の更新されたスクリプトです:

$("#callContact1").click(function() { 
 
    console.log('starting call back request'); 
 
    $.ajax({ 
 
     url: "https://www.server.com?type=makecall", 
 
     data: {}, 
 
     type: "GET" 
 
    }) 
 
    .then(function(data) { 
 
     $('#ajaxResponse').html(data).show(); 
 
     var httpStatus = (data.status); 
 
     var httpResponseCode = (data.getAllResponseHeaders); 
 
     console.log('httpStatus: ' + httpStatus); 
 
     console.log('httpResponseCode: ' + httpResponseCode); 
 
    }) 
 
    .fail(function(xhr) { 
 
     var httpStatus = (xhr.status); 
 
     var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus; 
 
     console.log('ajaxError: ' + ajaxError); 
 
     //make alert visible 
 
     $('#ajaxResponse').html(ajaxError).show(); 
 
    }) 
 
})

が、私は(要求が正常にかかわらず、実行された)、コンソールには何も届きません。私はまた、更新されたスクリプトの2行目の出力もコンソールに表示されていないことに気付きました。

+1

お使いのブラウザの履歴をクリアして、おそらくCORSについてコンソールで – JYoThI

+0

何かをしてみてください?またはAccess-Control- *ヘッダー? –

+0

ブラウザで再起動してもコンソールのエントリが表示されますが、期待値の代わりに「未定義」値が表示されています: httpStatus:未定義 httpResponseCode:未定義 – user982124

答えて

2

あなたはjQuery.ajaxのためのjQueryのドキュメントで見つけることができたよう)(

.then(function(data,status,xhr) { 
     $('#ajaxResponse').html(data).show(); 
     var httpStatus = status; 
     var httpResponseCode = (xhr.status); 
     console.log('httpStatus: ' + httpStatus); 
     console.log('httpResponseCode: ' + httpResponseCode); 
    }) 
0

に上記のコードを変更し

https://api.jquery.com/jQuery.ajax#jqXHR

あなたは(の.doneを使用することができます)と.fail() 2つのコールバック関数をパラメータとして使用して、成功と失敗の2つを組み込んだ.then()を使用して、

だから、あなたはこのように、SMTを使用することができます。

.then(function(data, status, xhr) { 
    $('#ajaxResponse').html(data).show(); 
    var httpStatus = status; 
    var httpResponseCode = (xhr.status); 
    console.log('httpStatus: ' + httpStatus); 
    console.log('httpResponseCode: ' + httpResponseCode); 
}, function(data, status, xhr) { 
    var ajaxError = 'There was an requesting the call back. HTTP Status: ' + status; 
    console.log('ajaxError: ' + ajaxError); //make alert visible 
    $('#ajaxResponse').html(ajaxError).show(); 

}) 
関連する問題