JS進級編6---原生JSパッケージajaxリクエスト

1833 ワード

一、原生JS中のajax
1.XMLHttpRequest非同期オブジェクトの作成
var xhr = new XMLHttpRequest()

2、コールバック関数の設定
xhr.onreadystatechange = callback

3、openメソッドを使用してサーバーと接続を確立する
// get   
xhr.open("get", "test.php", true)

// post               
xhr.open("post", "test.php", true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

4、サーバーにデータを送る
// get        
xhr.send(null)

// post       
xhr.send("name=javascript&age=18")

5.コールバック関数において異なる応答状態に対して処理する
function callback() {
  //          
  if(xhr.readyState == 4) {
    //         
    if(xhr.status == 200) {
      //           
      var res = xhr.responseText
      //     
      res = JSON.parse(res)
    }
  }
}

二、原生JSパッケージget要求
function get(){
    var xhr = window.xmlHttpRequest ? new xmlHttpRequest() : ActiveXObject("microsoft.XMLHttp");
    xhr.open("get","https://www.baidu.com/",true);
    xhr.send(null);
    
    xhr.onreadystatechange = function(){
        if(xhr.readystate == 4 && xhr.status == 200){
            console.log(xhr.responseText);
        }
    }
}

三、原生JSパッケージpost要求
function post(){
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("microsoft.XMLHttp")
    xhr.open("post","https://www.baidu.com/",true);
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
    xhr.send("name=javascript");
    
    xhr.onreadystatechange = function(){
        if(xhr.readystate == 4 && xhr.status == 200){
            console.log(xhr.responseText);
        }
    }
}