AJAX---發送GET請求並傳遞參數


GET請求

 

通常在一次 GET 請求過程中,參數傳遞都是通過 URL 地址中的 ? 參數傳遞

    var xhr = new XMLHttpRequest()
    // 這里任然是使用URL中的問號參數傳遞數據
    xhr.open('GET', 'users.php?id=2')
    xhr.send(null)

    xhr.onreadystatechange = function () {
      if (this.readyState !== 4 && this.state !== 200) return
      console.log(this.responseText)
    }

 

 

練習: 發送請求, 獲取列表數據, 呈現在頁面

    //獲取ul
    var ulList = document.getElementById('list')

    // 發送請求獲取列表數據呈現在頁面
    // =======================================

    var xhr = new XMLHttpRequest()

    xhr.open('GET', 'users.php')

    xhr.send()

    xhr.onreadystatechange = function () {
      if (this.readyState !== 4) return
      var data = JSON.parse(this.responseText)
      // data => 數據

      //遍歷循環,動態創建li, 把li添加到ul里面
      for (var i = 0; i < data.length; i++) {
        //動態創建li
        var liElement = document.createElement('li')
        //設置li的名字為接收到數據data的名字 name
        //設置li的id為接收到數據data的id
        liElement.innerHTML = data[i].name
        liElement.id = data[i].id
        //把li添加到ul里面
        ulList.appendChild(liElement)
        //給li添加點擊事件
        liElement.addEventListener('click', function () {
          // TODO: 通過AJAX操作獲取服務端對應數據的信息
          // 如何獲取當前被點擊元素對應的數據的ID
          // console.log(this.id)
          var xhr1 = new XMLHttpRequest()
          xhr1.open('GET', 'users.php?id=' + this.id)//獲取當前被點擊元素對應的數據的ID
          xhr1.send()
          xhr1.onreadystatechange = function () {
            if (this.readyState !== 4) return
            var obj = JSON.parse(this.responseText)
            alert(obj.age)
          }
        })
      }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM