1

I'm using the code below to do a POST request to an API and grab some data from the server

    request.open("POST", url, true);
    request.setRequestHeader("Content-type", "application/json; charset=UTF8");
    request.setRequestHeader("X-Accept", "application/json");
    request.send(JSON.stringify(data));

My issue is how to decide if I should do it asynchronous or synchronous. Well actually my issue with async is that I'm not sure how to apply an eventListener which would listen to the completion of that XHR.

If I use asynchronous calls my web application fetches the data too late and the application loads with the previously cache data, though If I use synchronous calls it takes about a second to fetch and display the data and I'm not sure how to display a "loading" icon since I'm not sure where to attach the eventListener.

Could someone make it clear on how to use XHR properly?

I'd like to mention that this is my first time trying to use XHR to fetch data from a server through an API.

4

1 に答える 1

3

ブラウザをフリーズせず、応答をより洗練された方法で処理できるため、非同期を使用してください。XHRの完了については、次を使用します。

request.open("POST", url, true);
request.onreadystatechange = function () {
    if (request.readyState === 4) {
        // XHR state is DONE
        if (request.status == 200) {
            // HTTP 200 status code (success)
            // HIDE YOUR "LOADING" SPINNER
            // use request.responseText to get the response's content
        }
    }
};
request.setRequestHeader("Content-type", "application/json; charset=UTF8");
request.setRequestHeader("X-Accept", "application/json");
request.send(JSON.stringify(data));
// SHOW YOUR "LOADING" SPINNER

いつものように、それに関するいくつかのドキュメントを読むことをお勧めします:https ://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest

「私のWebアプリケーションはデータを取得するのが遅すぎて、アプリケーションは以前にキャッシュされたデータをロードします」-それが何を意味するのか正確にはわかりませんが、上記のコードがどのように呼び出され/使用されているかを詳しく説明すると、私は適切に連携するように再編成できることを確認してください。

于 2013-01-25T02:45:21.553 に答える