ajax请求
jQuery
的$.ajax
仅仅是对XMLHttpRequest
进行了一下封装。
GET
jQuery
写法:
$.ajax('myservice/username', {
data: {
id: 'some-unique-id'
}
})
.then(
function success(name) {
alert('User\'s name is ' + name);
},
function fail(data, status) {
alert('Request failed. Returned status of ' + status);
}
);
Native XMLHttpRequest Object:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = function() {
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
上述代码在IE7+
浏览器工作正常,如果想要运行在IE6
的话,那么需要将new XMLHttpRequest()
替换为ActiveXObject("MSXML2.XMLHTTP.3.0")
POST
jQuery
写法:
var newName = 'John Smith';
$.ajax('myservice/username?' + $.param({id: 'some-unique-id'}), {
method: 'POST',
data: {
name: newName
}
})
.then(
function success(name) {
if (name !== newName) {
alert('Something went wrong. Name is now ' + name);
}
},
function fail(data, status) {
alert('Request failed. Returned status of ' + status);
}
);
Native XMLHttpRequest Object:
var newName = 'John Smith',
xhr = new XMLHttpRequest();
xhr.open('POST', 'myservice/username?id=some-unique-id');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== newName) {
alert('Something went wrong. Name is now ' + xhr.responseText);
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI('name=' + newName));
URL Encoding (URL 编码)
$.param({
key1: 'some value',
'key 2': 'another value'
});
Web API
提供两个有关URL encode
的方法:encodeURI
和encodeURIComponent
:
function param(object) {
var encodedString = '';
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (encodedString.length > 0) {
encodedString += '&';
}
encodedString += encodeURI(prop + '=' + object[prop]);
}
}
return encodedString;
}
发送和接受 JSON
jQuery
写法:
$.ajax('myservice/user/1234', {
method: 'PUT',
contentType: 'application/json',
processData: false,
data: JSON.stringify({
name: 'John Smith',
age: 34
})
})
.then(
function success(userInfo) {
// userInfo will be a JavaScript object containing properties such as
// name, age, address, etc
}
);
Web API:
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'myservice/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
}
};
xhr.send(JSON.stringify({
name: 'John Smith',
age: 34
}));
上述代码将会在IE8+
工作良好
上传文件
你应该知道在IE9
和低版本的浏览器里面唯一的上传方法是通过<form>
里面创建一个<input type="file">
。jQuery
并没有帮助你做了有关上传的所有事情。在现在的一些浏览器上,上传文件通常借助File API
。借助于这个API
,上传有两种方式:
<form enctype="multipart/form-data">
- 发送一个
body
包含file
数据的请求
给定下面的markup
:
<input type="file" id="test-input">
jQuery:
首先我们通过让文件作为multipart encoded request
的一部分来上传文件:
var file = $('#test-input')[0].files[0],
formData = new FormData();
formData.append('file', file);
$.ajax('myserver/uploads', {
method: 'POST',
contentType: false,
processData: false,
data: formData
});
我们也可以通过POST
一个含有文件的请求来上传:
var file = $('#test-input')[0].files[0];
$.ajax('myserver/uploads', {
method: 'POST',
contentType: file.type,
processData: false,
data: file
});
XMLHttpRequest:
作为form
的一部分上传:
var formData = new FormData(),
file = document.getElementById('test-input').files[0],
xhr = new XMLHttpRequest();
formData.append('file', file);
xhr.open('POST', 'myserver/uploads');
xhr.send(formData);
作为请求的一部分上传:
var file = document.getElementById('test-input').files[0],
xhr = new XMLHttpRequest();
xhr.open('POST', 'myserver/uploads');
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
CORS
CORS
就是发送跨源ajax
请求,这里有一点重要的是通过跨源ajax
请求,cookies
默认是不会被发送的,你必须设置XMLHttpRequest
上的withCredentials
变量,让我们看一眼:
$.ajax('http://someotherdomain.com', {
method: 'POST',
contentType: 'text/plain',
data: 'sometext',
beforeSend: function(xmlHttpRequest) {
xmlHttpRequest.withCredentials = true;
}
});
XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://someotherdomain.com');
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('sometext');
在IE8
或者IE9
中进行Cross-origin ajax requests
,只能使用IE-proprietary
:XDomainRequest
:
// For cross-origin requests, some simple logic
// to determine if XDomainReqeust is needed.
if (new XMLHttpRequest().withCredentials === undefined) {
var xdr = new XDomainRequest();
xdr.open('POST', 'http://someotherdomain.com');
xdr.send('sometext');
}
JSONP
你应该慎用或者少用JSONP
,因为它已经证明了存在一些安全问题,在现代浏览器中,使用CORS绝对是一种更好的路由选择。
JSONP
表示JavaScript Object Notation with Padding
,这项工作必须由服务器和客户端共同完成:
$.ajax('http://jsonp-aware-endpoint.com/user', {
jsonp: 'callback',
dataType: 'jsonp',
data: {
id: 123
}
}).then(function(response) {
// handle requested data from server
});
不使用 jQuery:
window.myJsonpCallback = function(data) {
// handle requested data from server
};
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src',
'http://jsonp-aware-endpoint.com/user?callback=myJsonpCallback&id=123');
document.body.appendChild(scriptEl);