原生的ajax请求


原生ajax请求的步骤:

get 请求:

1,创建一个xhr变量

 var xhr=new XMhttpRequest();

2,设置请求方式和请求地址

xhr.open('url','http//192.168.213.77:5000/login?username=" + str+ "&password=" + str')

3,把请求发出去;

xhr.send();

4,监听readystatechage

xhr.onreadystatechange = function () {
      // readyState请求准备状态, 共有4个值1-4, 1表示xhr创建  2表示数据处理完成  3表示请求已发送  4表示服务器返回结果,请求完成
      if (xhr.readyState == 4) {
        console.log(xhr.responseText)
        document.body.append(xhr.responseText)
      }
    }
}
 
 

post请求:

1,创建一个xhr变量

 var xhr=new XMhttpRequest();
 

2,设置请求方式和请求地址

xhr.open('url','http//192.168.213.77:5000/register)

 

在请求发之前,设置请求头中的数据类型为表单数据类型,否则服务器无法解析数据

 

xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded")
 
第四步: 把请求发出去, 参数是post请求的请求体, 也是键值对结构
    xhr.send("username=" + acc + "&password=" + pas)
 
第五步: 监听readystatechange
    xhr.onreadystatechange = function () {
      // readyState请求准备状态, 共有4个值1-4, 1表示xhr创建  2表示数据处理完成  3表示请求已发送  4表示服务器返回结果,请求完成
      if (xhr.readyState == 4) {
        console.log(xhr.responseText)
        document.body.append(xhr.responseText)
      }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM