2017-02-02 6 views
1

responseTypeが送信前に動的にjsonに設定されている場合、XMLHttpRequestレスポンスから「生の」(テキスト/データ)リクエスト?JavaScript XHR - responseTypeがjsonとして設定されている場合、レスポンスタイプが200以外の生データを取得

overrideMimeTypeと同じURLへの別のリクエストで条件付きで行うこともできますが、サーバーログや他のプロセスに関しては賢明ではないかもしれません。ここ

は一例であり:私のプロジェクトの実際のコードで

var xhr = new XMLHttpRequest(); 
 

 
xhr.open('GET','/some/path.wtf'); 
 
xhr.responseType = 'json'; 
 

 
xhr.onloadend = function() 
 
{ 
 
    if (this.status !== 200) 
 
    { 
 
    console.log(this.response); // null 
 
    // send the response-text to an error handler .. sigh :(
 
    return; 
 
    } 
 
}; 
 

 
xhr.send();

「/フォルダ/パス/」要求はJSONとの要求とみなされサーバーはJSONで応答します。問題がない限り、またはデバッグ/テストのためにclient.console.log()ルーチンが呼び出されました。

ご了承いただきますようお願い申し上げます。

+1

あなたはMDNのドキュメントを読みましたか? https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest – epascarello

+0

ありがとうepascarello、確かに:) – argon

答えて

0

次は、この問題の解決方法です。しかし、それは仕事は、周りにある- ブタが同じ問題に直面して他の人に役立つかもしれない:

var pth,ext,rsp,xhr; 
 

 
pth = '/some/path/'; 
 
rsp = ((path.substr(-1) == '/') ? 'json' : 'blob'); // for example 
 
xhr = new XMLHttpRequest(); 
 

 
xhr.patchJSON = ((rsp == 'json') ? 1 : 0); 
 
xhr.open('GET',pth); 
 
xhr.responseType = ((rsp == 'json') ? 'text' : rsp); 
 

 
xhr.onloadend = function() 
 
{ 
 
    if (this.status !== 200) 
 
    { 
 
    console.log(this.response); // response-text from server 
 
    // send the response-text to an error handler .. yayy :) 
 
    return; 
 
    } 
 

 
    if (this.patchJSON) 
 
    { 
 
    rsp = JSON.parse(this.response); 
 

 
    if ((rsp === null) && (this.response.trim().length > 0)) 
 
    { 
 
     console.log('json syntax error in: '+pth); 
 
     // send `rsp` to the error handler 
 
     return; 
 
    } 
 
    } 
 

 
    // handle blobs/markup/etc, -or: 
 
    console.log(rsp); 
 
}; 
 

 
xhr.send();

関連する問題