Ajax原生操作和Node js的操作?

606 阅读1分钟

AJAX 技术主要依靠 XMLHttpRequest (XHR) DOM 对象。它可以构造 HTTP 请求、发送它们,并获取请求结果

Ajax原生操作的步骤:

// 1.创建对象 
const xhr=new XMLHttpRequest();
// 2.请求地址
const url="";
// 3.初始化请求  (如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:)
xhr.open("method","url")
// 4.发送请求
xhr.send()
// 5.监听状态变化  当readystate属性的值变化时,执行onreadystatechange属性指向的回调函数
xhr.onreadystatechange=()=>{
    if(xhr.readyState==4&&xhr.status==200){
        console.log("xhr.response");
    }
}
node  js
// 引入模块
const XMLHttpRequest=require('xmlhttprequest-ssl').XMLHttpRequest;
// 1.创建对象 
const xhr=new XMLHttpRequest();
// 2.请求地址
const url='http://192.168.1.24:8080/wx/category/list';
// 3.初始化请求  (如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:)
xhr.open("get",url);
// 4.发送请求
xhr.send(null);
// 5.请求完成时才能执行
xhr.onload=()=>{
    console.log('----->'+xhr.readyState);
    if(xhr.status==200){
        console.log(xhr.responseText);
     }else{
         console.log('请求出错!');
     }
}