Ajax的解释
Ajax:async javascript and xml(异步的JavaScript和xml)
用于浏览器和后台服务进行异步交互(传递信息)
特点
1.不会导致页面的全局刷新就可以进行与后台的交互
2.交互需要在”查看元素 -> 网络”中监控
使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| XMLHttpRequest 1. 实例化 var xhr = new XMLHttpRequest(); 2. 设置请求 xhr.open(method,url); 3. 设置头信息 xhr.setRequestHeader() 4. 设置体信息(method为post时候) xhr.send(data);
5. 设置监听 xhr.onreadystatechange = function(){ this.readyState this.status this.response }
200 ok 404 找不到资源 500 后台异常
|
举例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| var $ = { get : function(url,handler){ var xhr = new XMLHttpRequest(); xhr.open("get",url); xhr.responseType = "json"; xhr.send() xhr.onreadystatechange = function(){ if(this.readyState === 4){ if(this.status === 200){ var response = this.response; handler.call(this,response) } } } }, post : function(url,data,handler,type){ var xhr = new XMLHttpRequest(); xhr.open("post",url); xhr.responseType = "json"; if(!type){ type = "application/x-www-form-urlencoded"; } xhr.setRequestHeader("Content-Type",type) xhr.send(data) xhr.onreadystatechange = function(){ if(this.readyState === 4){ if(this.status === 200){ var response = this.response; handler.call(this,response) } } } } }
|
HTTP请求报文
1 2 3 4 5 6 7
| 请求行 GET / HTTP/1.1 请求头信息 Content-Type:application/x-www-form-urlencoded Content-Size:1204 ... 请求体信息(post参数)
|
HTTP响应报文
1 2 3 4 5 6 7 8 9
| 响应行 HTTP/1.1 200 OK 响应头 Server: Apache Content-Length: 29769 Content-Type: text/html ... 响应体 <!DOCTYPE html...
|
jQuery中的Ajax【基于回调函数】
1.速写方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| $.get(url[,data][,success][,dataType]) 以get方式请求 url 请求地址 data 请求参数,对象 success 回调函数 dataType responseType => $.ajax(url,{ method:"get", success:function(){}, data:data, dataType:'json' })
$.post(url[,data][,success][,dataType]) 以post方式请求 url 请求地址 data 请求参数,对象 success 回调函数 dataType responseType => $.ajax(url,{ method:"post", success:function(){}, data:data, dataType:'json' })
|
2.低级别接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $.ajax(url,settings) settings是一个对象,配置信息; async 异步,true; beforeSend 回调函数,在请求发送前调用 complete 回调函数,请求接受后调用 success 回调函数,请求成功后 error 回调函数,请求结束后 contentType 参数类型,默认为querystring 默认值application/x-www-form-urlencoded 如果参数为json,要改为application/json processData boolean,默认将data转换为查询字符串 如果参数为json,要将其设置为false data 对象,参数 如果参数为json;JSON.stringify(对象) dataType responseType,json/xml/script... headers 对象,setRequestHeader(key,val) method 请求方式,get/post
|
如何使用jQuery发送json数据?
1 2 3 4 5 6 7 8 9 10
| xhr.setRequestHeader("Content-Type","application/json"); xhr.send(JSON.stringify(data)) => $.ajax(url,{ method:"post", contentType:"application/json", processData:false, data:JSON.stringify(参数对象), success:function(){} })
|