原生的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)
      }
    }
posted @ 2022-03-11 18:55  俺是前端小菜  阅读(2355)  评论(0编辑  收藏  举报