jq中的ajax比原生中的好用多了,都是使用一个对象就可以了。
<button>获取新闻列表</button>
<ul class="wrapper"></ul>
<script src="http://code.jquery.com/jquery-3.4.1.js"></script>
<script>
$('button').click(function() {
$.ajax({
type: 'GET', // 请求方式(默认)
url: './getNews.php', // 地址
success: function(data) { // 成功回调
console.log(data);
console.log(this);
var data = JSON.parse(data);
var str = '';
$.each(data, function(index, ele) {
str += `<li>${ele.title}</li>`;
});
$(this).append(str);
},
error: function(err) {
console.log(err)
},
async: true, // 异步(默认)
// data: 'username=fanghuayong&age=18', //POST的时候用 可写对象形式 也可写字符串形式
cache: false, // 不要缓存
context: $('.wrapper')[0], // 设置Ajax相关回调函数的上下文 ajax中的指向 默认指向ajax
headers: {name: 'fanghuayong'}, // 后端需要的请求头
})
})
</script>
在jQuery的Ajax中使用JSONP
$('button').click(function() {
$.ajax({
type: 'GET', // 请求方式(默认)
url: 'https://www.baidu.com/sugrec', // 地址
data: 'prod=pc&wd='+$('input').val(), //POST的时候用 可写对象形式 也可写字符串形式
crossDomain: true, // 同域请求为false 跨域请求为true
dataType: 'jsonp', // 预期服务器返回的数据类型 xml html script json jsonp text
jsonp: 'cb', // 需要给后端传的回调名
jsonpCallback: 'asdf', // 回调名
})
})
function asdf(data) {
console.log(data);
}

Deferred和Ajax的使用:
success和error字段弃用。
$('button').click(function() {
$.ajax({
type: 'GET', // 请求方式(默认)
url: './getNews.php', // 地址
}).done(function (data) {
console.log(data)
}).fail(function (err) {
console.log(err)
})
})
再改进: 按顺序执行
$('button').click(function() {
$.ajax({
type: 'GET', // 请求方式(默认)
url: './getNews1.php', // 地址
}).then(function (data) {
console.log(data)
}, function (err) {
console.log(err)
})
})

always() 不管成功还是失败统一执行。
$('button').click(function() {
$.ajax({
type: 'GET', // 请求方式(默认)
url: './getNews.php', // 地址
}).always(function (data) {
console.log(data);
})
})

还有
jQuery.get()
jQuery.post()
的简写。