Ajax使用

  Ajax使用

一:启动终端:

  npm i express:下载express框架

二:Ajax请求:

//大前提:有一个htmnl的网页,还有一个result的文本等待通过按钮使用Ajax来获取文本
var result;
document.getElementById(){}//你懂的
//创建Ajax来获取服务器端口result的值
//1.创建XMLHttpRequest异步对象
var xhr;
if(window.XMLHttpRequest)
    xhr=new XMLHttpRequest();
//2.设置回调函数,初始化,设置请求方法和url:
xhr.open('GET/POST','http://127.0.0.1:5000/server');
//3.发送:
xhr.send();
//4.事件绑定,处理服务器返回的结果
//on when,readystate是xhr对象中的属性,表示状态有01234
xhr.onreadystatechange=function(){
    //判断相应状态:200,404,403
    if(xhr.status>=200&&xhr.status<300){
        //处理返回结果 :包括行,头,空行,体
        //1.响应行
        console.log(xhr.status);//状态码
        console.log(xhr.statusText);//状态字符串
        console.log(xhr.getAllResponseHeaders());//所有响应头
        
        //赋值给result文本,假设响应成功,且回来是以字符串的方式回来
        result,innerHtml=xhr.response;
    }
}
原文地址:https://www.cnblogs.com/instead-everyone/p/13835814.html