js 實現ajax(get和post)


get和post的區別:
1.GET產生一個TCP數據包;POST產生兩個TCP數據包。
  對於GET方式的請求,瀏覽器會把http header和data一並發送出去,服務器響應200(返回數據);
  而對於POST,瀏覽器先發送header,服務器響應100 continue,瀏覽器再發送data,服務器響應200 ok(返回數據)。
2.get請求數據有限制,post請求數據沒有限制
3.請求參數在url中發送,post請求參數在http消息主體中發送

    //get
      function get() {
          //創建XMLHttpRequest
        let xhr = new XMLHttpRequest();
          //監聽響應
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
            console.log(xhr.responseText);
          }
        };
        xhr.open("GET","your url",true);
        xhr.send();
      }

      //post
      function post () {
          //請求參數、url、創建XMLHttpRequest
        let data = 'name=tom&age=18',
          url = 'your url',
          xhr = new XMLHttpRequest();

        xhr.open('post', url);
          //設置header
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send(data);
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && ( xhr.status === 200 || xhr.status === 304 )){
            console.log(xhr.responseText);
          }
        }
      }

 

 

參考:1.https://blog.csdn.net/u012391923/article/details/53197387?utm_source=blogxgwz3
   2.http://www.runoob.com/tags/html-httpmethods.html


免責聲明!

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



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