jQuery进行 Ajax 调用
如果 jQuery 的 .ajax()
方法要支撑所有 jQuery 异步请求,则必须非常强大。以下是简单的 Ajax 请求:
$.ajax({
url: 'http://swapi.co/api/people/1/'
});
在设置 XHR 对象时,响应由一个函数处理的,.ajax()
方法也一样。我们可以使用 .done()
方法链接到 .ajax()
。我们向 .done()
方法传入一个当 Ajax 调用完成时将运行的函数!
function handleResponse(data) {
console.log('the ajax request has finished!');
console.log(data);
}
$.ajax({
url: 'http://swapi.co/api/people/1/'
}).done(handleResponse);
所以普通的XHR方法:
const imgRequest = new XMLHttpRequest();
imgRequest.onload = addImage;
imgRequest.open('GET', `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`);
imgRequest.setRequestHeader('Authorization', 'Client-ID <your-client-id-here>');
imgRequest.send();
可以利用简化为:
$.ajax({
url: `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`
}).done(addImage);