jq: Ajax

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);
}

      

v2-a73b3fc87584824797f8192c1f8fb45e_b.jpg

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)
    })
 })

      

v2-2fa62268a2dead3077017bdcd8f903ae_b.jpg

always() 不管成功还是失败统一执行。

        $('button').click(function() {
    $.ajax({
        type: 'GET', // 请求方式(默认)
        url: './getNews.php', // 地址
    }).always(function (data) {
        console.log(data);
    })
})

      

v2-7ffe35ab18d62993132df03133d9611f_b.jpg


还有

jQuery.get()

jQuery.post()

的简写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值