AJAX

AJAX
Ajax技术核心是XMLHttpRequest对象(简称XHR)
IE7+、Firefox、Opera、Chrome和Safari都支持原生的XHR对象,在这些浏览器中创建XHR对象可以直接实例化XMLHttpRequest即可。
var xhr = new XMLHttpRequest();    
alert(xhr);


与服务器通信的API就是XMLHttpRequest
都需要那些步骤来通信呢,简单理解一共只有4步	
1、新建XMLHttpRequest对象
var request=new XMLHttpRequest();
IE 7以下 var request=new ActiveXObject("Microsoft.XMLHTTP");
2、打开要发送的地址通道。
    request.open(“GET”,地址,同步/异步);
3、给XMLHttpRequest对象增加侦听器,用来侦听各种情况,包括各种链接状态
    request.addEventListener(“load”,侦听函数)发送数据给打开的地址
4、如果没有要发送的内容直接send()
    request.send();


数据提交给服务器有两种方式:
第一种:
表单提交,通过表单submit触发,提交到form中action属性地址,使用的方法是methed给出
这种方式有个缺陷,需要跳转页面
第二种:
通过ajax提交的,就不能触发submit,而是通过按钮点击,直接使用ajax发送给服务端
发送到的地址就是open中的第二个参数,发送方法就是open的第一个参数
不需要跳转页面,缺陷,部分内容无法进行SEO优化
以上情况只能二选一
GET和POST请求方式
GET:通过地址栏后面 ? 带入字符串,字符串格式是变量=值&变量=值的方式传递数据给服务器
     这种传送方式仅仅是去服务端获取,没有单独传递数据,并且从服务端获取需要内容,这个就是GET
     传递给服务器的数据少,而且是明文传递,只能使用字符串,并且数据无法进行多样性嵌套
     如果地址是当前页面锚点是可以提交页面
POST:数据不是通过地址栏发送,通过数据握手后信道发送数据,并且会将数据转换为二进制数据发送给服务器
    传送数据可以是任意复杂度数据,但是传送的数据类型,包含了字符串,二进制流其它一些格式
    
如果使用GET方式发送,数据会写在url后面?后面的内容
如果使用POST方法发送,数据会被写在send中
// 在使用表单提交时,是跳转页面,跳转就不需要考虑来回的问题,所以不牵扯跨域
// 但是ajax是访问别的网站并且将数据取回,这就需要考虑跨域的问题
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
// open(method,url,async,userName,password);
// url:表示发送的地址,如果GET方式,可以在地址后面增?参数=值传递数据
// open的第三个参数是async异步,默认是true,默认是异步返回数据,如果设置fasle,表示同步等待
// open的第四个参数和第五个参数是用户名和密码,有些地址访问是需要用户名和密码
xhr.open("POST","http://localhost:4010/a.php");
// 如果直接同post发送给php,php无法接收到数据
// 设置请求头,如果前端需要通过POST发送数据给php页面,就需要写这个请求头,给nodejs服务发送POST请求时不用写
// 这个请求头必须写在open之后,send之前
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.send("user=张三");

function loadHandler(e){
    console.log(this.response);
}
1\表单提交还是ajax发送,表单不需要跨域, ajax需要考虑跨域
2\使用GET还是使用POST,数据发送的形式不同,一个是地址后缀,一个是send发送
3\如果使用POST,是发送给NodeJs还是发送给PHP ,服务器语言不同,处理方式不同
4\AJAX--->POST--->PHP 需要写请求头xhr.setRequestHeader

如果访问node直接访问域名端口号
如果访问php,jsp,一般带有文件名
请求本地数据 AJAX不单纯可以请求服务器数据,还可以请求本地数据
加载本地文件
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.text");
xhr.send();
function loadHandler(e){
    // response返回的数据
    // console.log(this.response);
    // 获取div标签元素
    var div=document.querySelector("div");
    // 将本地返回过来的数据写入到div容器中
    div.textContent=this.response;
}
加载外部的json文件,注意只能读取,不能写入
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./config.json");
xhr.send();
function loadHandler(e){
    // 将返回过来的数据转换为对象
    var obj=JSON.parse(this.response);
    console.log(obj.backgroundColor);
    document.documentElement.style.backgroundColor=obj.backgroundColor;
}
加载外部XML文件
// XML是全语言共通数据
// 注意书写格式规范
// 缺陷是数据太大
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.xml");
xhr.send();
function loadHandler(e){
    xml=xhr.responseXML;
    // 获取标签名里的文本内容
    // var num=xml.getElementsByTagName("num")[0].textContent;
    // var na=xml.getElementsByTagName("NA")[0];
    var na=xml.querySelectorAll("NA>man")[0];
    console.log(na.getAttribute("name"));
}
加载图片
// 加载图片数据发送给服务端,服务器接收到后转换为图片文件存储起来
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./img/2.jpg");
xhr.send();
function loadHandler(e){
    console.log(this.response);
}
加载html
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.html");
xhr.send();
function loadHandler(e){
    // console.log(this.response);
    var div=document.querySelector("div");
    // 插入返回的数据
    div.innerHTML=this.response;
}
同步和异步
异步
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010/a.php");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("user=zhangsan");
console.log("a");
function loadHandler(e){
    console.log(this.response);
    console.log("b");
}
console.log("c");
阻塞式同步
var xhr=new XMLHttpRequest();
// open的第三个参数是async异步,默认是true,默认是异步返回数据,如果设置为fasle,表示同步等待
xhr.open("POST","http://localhost:4010/a.php",false);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("user=weizheng");
console.log("a");
// 阻塞式同步,等待数据返回后,继续执行
console.log(xhr.response);
console.log("c");
请求消息:客户端发送给服务端的消息
响应消息:服务端发送给客户端的消息
// 请求消息中需要裹挟着一些说明型的数据,让服务端收到后根据这些数据比对和解析
// 这种数据一般比请求消息更早的发送到服务端,服务端就可以解析了,这种数据就是请求头
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010/a.php");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
// 在ajax中设置请求头通过xhr.setRequestHeader(请求头名,请求头值);
// 可以写多条语句设置
xhr.setRequestHeader("names","zhangsan");
xhr.send("user=zhangsan");
function loadHandler(e){
    console.log(this.response);
}
在客户端中可以设置请求头和获取响应头
在服务端中可以获取请求头和设置响应头
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
// 这个是自定义的请求头,如果跨域时,请求头也必须设置允许跨域才可以发送
// xhr.setRequestHeader("names","weizheng");
xhr.setRequestHeader("dataType","json");
// 设置请求头必须写在open和send之间
xhr.send("user=zhangsan");

function loadHandler(e){
    // 获取所有响应头消息
    console.log(xhr.getAllResponseHeaders());
    // 获取指定的响应头消息
    console.log(xhr.getResponseHeader("content-type"));
}
send()发送
发送JSON字符串
var obj={
    user:"weizheng",
    age:21
}
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
// 通过JSON字符串进行发送
xhr.send(JSON.stringify(obj));
function loadHandler(e){

}
上传Blob(二进制)数据,比如图片文件等
var form=document.querySelector("form");
form.addEventListener("submit",submitHandler);

function submitHandler(e){
    e.preventDefault();
    var file=document.querySelector("[type=file]");
    // files是一个数组,它是一个二进制数据
    // console.log(file.files);
    // 上传文件
    var xhr=new XMLHttpRequest();
    xhr.open("POST","http://localhost:8000");
    xhr.addEventListener("load",loadHandler);
    xhr.send(file.files[0]);

    var xhr=new XMLHttpRequest();
    xhr.open("POST","http://localhost:8000");
    xhr.addEventListener("load",loadHandler);
    xhr.send(file.files[1]);

    var xhr=new XMLHttpRequest();
    xhr.open("POST","http://localhost:8000");
    xhr.addEventListener("load",loadHandler);
    xhr.send(file.files[2]);
}

function loadHandler(e){
    console.log(this.response);
} 
直接发送document或者可以直接将HTML发送给服务器
var x=new XMLHttpRequest();
x.addEventListener("load",xmlLoadHandler);
x.open("GET","./a.xml");
x.send();

function xmlLoadHandler(e){
    // console.log(x.responseXML);
    var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("POST","http://localhost:8000");
    xhr.send(x.responseXML);
}

function loadHandler(e){

}
formData 发送表单数据
var form=document.querySelector("form");
form.addEventListener("submit",submitHandler);

function submitHandler(e){
    e.preventDefault();
    var fd=new FormData(form);
    // 遍历表单所有数据
    // for(var values of fd){
    //     console.log(values);
    // }
    var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("POST","http://localhost:8000");
    // 将整个表单数据提交
    xhr.send(fd);
}

function loadHandler(e){

}
timeout 超时,因为各种因素导致数据前后端传递的延迟
设置时间等待,如果超过这个时间,就切断数据发送
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:8000");
xhr.addEventListener("load",loadHandler);
// 超时事件,如果触发超时等待就会执行这个事件
xhr.addEventListener("timeout",tiemOutHandler);
// 设置超时等待2秒
xhr.timeout=2000;
xhr.send("超时等待");

function loadHandler(e){

}

function tiemOutHandler(e){
    xhr.abort();// 将原来的连接断掉
    // 重新再创建并执行新的xhr的通信
}
readystate
var xhr=new XMLHttpRequest();
// 在整个AJAX的通信中属于全过程监听,当状态改变时,触发该函数
xhr.addEventListener("readystatechange",readyStateHandler);
xhr.open("POST","http://localhost:8000");
xhr.send("aaa");
值   状态                描述
0    UNSENT              代理被创建,但尚未调用open()方法
1    OPENED              open()方法已经被调用
2    HEADERS_RECEIVED    send()方法已经被调用,并且头部和状态已经可获得
3    LOADING             下载中;responseText()属性已经包部分数据
4    DONE                下载操作已完成


当一个文档的 readyState 属性发生更改时,readystatechange 事件会被触发。
状态主要分
1、信息  100-101
2、成功  200-206
3、重定向  300-307
4、客户端错误 400-417
5、服务器错误  500-505
function readyStateHandler(e){
    console.log(this.readyState,this.status);
    if(this.readyState===4 && this.status===200){
        // console.log(this.readyState);
        console.log(this.response);
    }
}

获取表单内容,在页面显示

发送数据给服务端,接受服务端返回过来的数据(GET发送方式)
css样式
#div0{
    width: 100px;
    height: 100px;
    position: absolute;
    right: 0;
    top: 0;
    font-size: 30px;
}

<form action="http://localhost:4010" method="GET">
    <label>user</label>
    <input type="text" name="user"><br>
    <label>password</label>
    <input type="password" name="password"><br>
    <label>x</label>
    <input type="text" name="x"><br>
    <label>y</label>
    <input type="text" name="y"><br>
    <button type="submit">提交</button>
</form>
<div id="div0"></div>

// 获取表单元素
var form=document.querySelector("form");
// 获取所有input标签元素
var inputs=document.querySelectorAll("input");
// form表单添加提交事件
form.addEventListener("submit",submitHandler);

function submitHandler(e){
    // 取消默认事件
    e.preventDefault();
    // 将对应文本框里面的结果值赋给定义的变量
    var user=inputs[0].value;
    var password=inputs[1].value;
    var x=inputs[2].value;
    var y=inputs[3].value;
    var url="http://localhost:4010?user="+user+"&password="+password+"&x="+x+"&y="+y;
    ajax(url);
}

function ajax(url){
    // 创建ajax对象
    var xhr=new XMLHttpRequest();
    // 侦听加载消息,服务端发送给客户端的消息执行loadHandler
    xhr.addEventListener("load",loadHandler);
    // 对象打开通道("以什么方式发送GET/POST","要访问的地址");
    xhr.open("GET",url);
    // 发送
    xhr.send();
}

function loadHandler(e){
    // 这个服务端发回来的消息
    console.log(this.response);
    var div0=document.getElementById("div0");
    // 将发过来的消息写入到div容器中
    div0.textContent=this.response;
}
处理客户端请求的内容,再将内容发送给客户端
// 导入http的api,主要用来做http通信
// 导入一个模块http
// http内置模块自动生成
// 默认导入的就是js,不用写后缀了
var http=require("http");
// 封装的方法解析字符串
var query=require("querystring");
// 完成http通信中创建一个服务,自带一个函数,函数里面包括两个参数
// req 请求消息对象,客户端发送给这个node服务的信息
// res 响应消息对象,这个node服务要发送给客户端的信息
var server=http.createServer(function(req,res){
    // node中不能使用事件,所以事件方式使用on来侦听
    // 这个事件表示请求消息对象侦听事件,当客户端发送的数据传送到node服务获得数据时,执行下面的函数
    req.on("data",function(){

    });
    // end 就是当所有的客户端消息给node服务发送接收完成,执行下面的函数
    req.on("end",function(){
        // http://localhost:4010/main.php?user=weizheng&age=21&sex=man
        // req.url 客户端请求发送地址
        // 截取url?后面的内容
        var str=req.url.split("?")[1];
        // 将截取的json字符串转换为对象
        var obj=query.parse(str);
        // 对象里面的x,y属性值相加转换为数值
        var sum=Number(obj.x)+Number(obj.y);
        // --------------以上都是处理客户端发过来的数据

        // --------------下面的内容就是服务端发送给客户端的内容
        // 发送给客户端的内容
        // 给响应的消息对象中写入要发送的内容
        // 设置响应消息头
        // 200 表示返回访问成功
        res.writeHead(200,{
            // 设置响应头的文本内容及编码
            "content-type":"text/html;charset=utf-8",
            // 设置允许跨域的访问的地址,* 是通配符,代表任何人可以访问
            "Access-Control-Allow-Origin":"*"
        })
        // write写入
        res.write(sum.toString());
        // 接受数据完成,执行发送
        res.end();
    });
})

// 侦听
server.listen(4010,"localhost",function(){
    console.log("开启了服务");
})
发送数据给服务端,接受服务端返回过来的数据(POST发送方式)
css样式
#div0{
    width: 100px;
    height: 100px;
    position: absolute;
    right: 0;
    top: 0;
    font-size: 30px;
}

<form action="http://localhost:4010" method="GET">
    <label>user</label>
    <input type="text" name="user"><br>
    <label>password</label>
    <input type="password" name="password"><br>
    <label>x</label>
    <input type="text" name="x"><br>
    <label>y</label>
    <input type="text" name="y"><br>
    <button type="submit">提交</button>
</form>
<div id="div0"></div>

var form=document.querySelector("form");
    var inputs=document.querySelectorAll("input");
    form.addEventListener("submit",submitHandler);

    function submitHandler(e){
        e.preventDefault();
        var user=inputs[0].value;
        var password=inputs[1].value;
        var x=inputs[2].value;
        var y=inputs[3].value;
        var str="user="+user+"&password="+password+"&x="+x+"&y="+y;
        ajax(str);
    }

    function ajax(str){
        // 创建ajax对象
        var xhr=new XMLHttpRequest();
        // 侦听加载消息,服务端发送给客户端的消息执行loadHandler
        xhr.addEventListener("load",loadHandler);
        // 对象打开通道("以什么方式发送GET/POST","要访问的地址");
        xhr.open("POST","http://localhost:4010");
        // 发送
        xhr.send(str);
        // 如果使用GET方式发送,数据会写在url后面?后面的内容
        // 如果使用POST方法发送,数据会被写在send中
    }

    function loadHandler(e){
        // 这个服务端发回来的消息
        console.log(this.response);
        var div0=document.getElementById("div0");
        div0.textContent=this.response;
    }
处理客户端请求的内容,再将内容发送给客户端
// 导入http的api,主要用来做http通信
var http=require("http");
var query=require("querystring");
// http中创建一个服务,自带一个函数
// req 请求消息对象,客户端发送给这个node服务的信息
// res 响应消息对象,这个node服务要发送给客户端的信息
var server=http.createServer(function(req,res){
    // 事件方式使用on来侦听
    // 这个事件表示请求消息对象侦听事件,当客户端发送的数据传送到node服务获得数据时,执行下面的函数
    // 当前端使用post发送数据时,数据不在url中,而在data中
    var str="";
    req.on("data",function(_data){
        // "user="+user+"&password="+password+"&x="+x+"&y="+y;
        // 将带过来的数据转换为字符串
        str=_data.toString();
    });
    // end 就是当所有的客户端消息给node服务发送接收完成,执行下面的函数
    req.on("end",function(){
        // 字符串转换为对象
        var obj=query.parse(str);
        var sum=Number(obj.x)+Number(obj.y);
        // 上面都是处理客服端发过来的数据
        // 下面的内容都是服务端发送给客户端的信息
        // 给响应的消息对象中写入要发送的内容
        // 设置响应消息头
        // 200 表示返回访问成功
        res.writeHead(200,{
            // 设置响应头的文本内容及编码
            "content-type":"text/html;charset=utf-8",
            // 设置允许跨域的访问的地址,* 是通配符,代表任何人可以访问
            "Access-Control-Allow-Origin":"*"
        })
        res.write(sum.toString());
        // 接受数据完成,执行发送
        res.end();
    })
})

server.listen(4010,"localhost",function(){
    console.log("开启了服务");
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值