Fork me on GitHub

jqurey中ajax的使用

为了工作和平时项目的需要,在自己工作空余时间自己写的一个css样式
同时也是为了巩固知识。

1、在jqurey中的ajax

引入jqurey.js

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
<div class="text-root">
//数据显示位置
</div>
<script>
$.ajax({            
url: "数据接口地址",
dataType: "json", //数据格
type: "get/post", //请求方式
async: false, //是否异步请求
success: function(data)
{   //如果请求成功,返回数据。
           
$(".text-root").text(data);            
},
complete: function() {
//请求完成的处理
},
"error": function(result)
{
//请求失败处理
var response = result.responseText;
alert('Error loading: ' + response);
}
});     
<script>

2、ajax 请求过程:(JS)

1、创建 XMLHttpRequest 对象、连接服务器、发送请求、接收响应数据;

1
2
3
4
5
6
7
8
9
10
var xhr = function createXhr(){
if(window.ActiveXObject){ //IE5 IE6
return new window.ActiveXObject("Microsoft.XMLHttp");
}else if(window.XMLHttpRequest){ //IE7 以上 及 其他浏览器
return new XMLHttpRequest();
}else{
alert("您的浏览器不兼容,换一个");
return null;
}
}

2、准备向服务端发请求,open()

1
2
3
4
5
6
7
if(xhr!=null){    
//如果实例化成功,就调用open()方法,就开始准备向服务器发送请求
xhr.open("post", url, true);
/*三个参数:第一个是发送请求的类型,POST 和GET 两种
第二个是url的地址,(地址也可以是静态文件,xml文件)
第三个,是否是异步,true是 异步。false 是同步*/
}

3、回调函数的处理(数据接收的处理)

1
2
3
4
5
xhr.onreadystatechange = processResponse; //指定响应函数  

function processResponse() {

}

4、发送

1
xhr.send();

注意几个书写的顺序:

1
2
3
4
5
6
7
8
9
10
11
12
var xhr = createXMLHttpRequest();
xhr.open("GET","test.jsp",true);
xhr.OnreadyStateChange = function(){
if(xhr.readyState==4&&xhr.status==200){
//通过responseXML和responeText来获取信息
var doc = xhr.responseXML;//responseXML只能获取XML格式
(var doc = xhr.responseText)


}
}
xhr.send();

详细说明

-------------本文结束感谢您的阅读-------------