Fork me on GitHub

原生ajax

原生ajax写法和jsonp的简单实现

创建XMLHttpRequest对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function createXMLHTTPRequest() {
//1.创建XMLHttpRequest对象
//需要针对IE和其他类型的浏览器建立这个对象的不同方式写不同的代码
var xmlHttpRequest;
if (window.XMLHttpRequest) {
//针对FireFox,Mozillar,Opera,Safari,IE7,IE8
xmlHttpRequest = new XMLHttpRequest();
//针对某些特定版本的mozillar浏览器的BUG进行修正
} else {
//针对IE6(用ie6的公司,还是别去了。。会哭)
xmlHttpRequest= new ActiveXObject('Microsoft.XMLHTTP');
}
return xmlHttpRequest;
}

ajax的get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function get(){
var req = createXMLHTTPRequest();
if(req){
req.open("GET", "http://test.com/?keywords=手机", true);
req.onreadystatechange = function(){
if(req.readyState == 4){
if(req.status == 200){
alert("success");
console.log(req.response)//如果返回的是字符串,则需要JSON.parse(),转换成js对象
}else{
alert("error");
}
}
}
req.send(null);
}
}

ajax的post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function post(){
var req = createXMLHTTPRequest();
if(req){
req.open("POST", "http://test.com/", true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gbk;");
req.send("keywords=手机");
req.onreadystatechange = function(){
if(req.readyState == 4){
if(req.status == 200){
alert("success");
console.log(req.response)//如果返回的是字符串,则需要JSON.parse(),转换成js对象
}else{
alert("error");
}
}
}
}
}

post请求需要设置请求头

ajax的jsonP请求

在介绍jsonp之前,首先我们来了解下同源策略。同源策略阻止从一个域上加载的脚本获取或操作另一个域上的文档属性。也就是说,受到请求的 URL 的域必须与当前 Web 页面的域相同。这意味着浏览器隔离来自不同源的内容,以防止它们之间的操作。

这时我们就需要jsonp来做跨域操作(有时候也需要服务端支持).主要是利用script标签内的src可以跨域来实现

1
2
3
4
5
6
7
8
9
10
function wellFn(data){
console.log(data)
}//在js中做的回调函数
var xmlJs = document.createElement("script");
xmlJs.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=%E6%B5%B7%E8%B4%BC%E7%8E%8B&json=1&cb=wellFn";//这时百度搜索的一个请求,wd后面跟要搜索的关键字;cb后面跟你的回调函数
document.getElementsByTagName("head")[0].appendChild(xmlJs)//把script插入到页面中,当你打开页面时候控制台就会出现你请求的json
-------------本文结束感谢您的阅读-------------