LoginSignup
0
0

More than 1 year has passed since last update.

Ajax(非同期通信)

Posted at

GETで通信

var xhr = new XMLHttpRequest();

xhr.open('GET', http://xxx?param=value);
xhr.send();

xhr.onreadystatechange = function() {

    if(xhr.readyState === 4 && xhr.status === 200) {
        //処理
    }
}

POSTで通信

var xhr = new XMLHttpRequest();

xhr.open('POST', http://xxx);
xhr.send('param=value');

xhr.onreadystatechange = function() {

    if(xhr.readyState === 4 && xhr.status === 200) {
        //処理
    }
}

イベント毎に非同期通信をする場合の例(入力がある毎に通信)

function_ajax();
function function_ajax() {

    var xhr = new XMLHttpRequest();

    const $input = document.querySelector('#id');
    //#idを持たないページはここで処理が終わる
    if (!$id) {
        return;
    }

    $input.addEventListener('input', function () {

        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                //処理
            }
        }

        xhr.open('GET', 'http://xxx?param=value');
        xhr.send();
    });
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0