AJAX原生代码

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

整个过程是异步,不需要等待服务器返回数据,才执行后面的内容。

function ajax(url,fn){
                //创建xhr对象
                var xhr = new XMLHttpRequest()
                
                //设置发送的服务器地址和方法
                xhr.open("GET",url)
                
                //发送
                xhr.send()
                
                //xhr状态改变的事件进行监听
                xhr.onreadystatechange = function(){
                    console.log("readyState:"+xhr.readyState)
                    console.log("status"+xhr.status)
                    if(xhr.readyState==4&&xhr.status==200){
                        fn(xhr)
                    }
                }
            }

调用:

    ajax("./recommend.json",function(xhr){
                console.log(xhr)
                var jsonObj = JSON.parse(xhr.responseText)
                console.log(jsonObj)
                
                var arr =  jsonObj.list;
                console.log(arr)
                arr.forEach(function(item,index){
                    var div = document.createElement("div")
                    div.innerHTML = `<h3><a href="https://www.bilibili.com/video/av${item.aid}/"> ${item.title}</a></h3><p>${item.description}</p>`
                    document.body.appendChild(div)
                })
                
            })

 

jQuery_Ajax

原生Ajax的步骤:

Xhr->xhr.open(get,url)->xhr.send->xhr.onrealystatechange

jQuery_Ajax:

语法:

$.get(url).then(function(res){获取内容执行的函数})

$.post(url).then(function(res){获取内容执行的函数})

不分方法:

$.ajax({

         url:"服务器地址",

         method:"请求方法",

         data:{//传给服务器的参数

location:$("#city").val(),

                            key:'c8b18212397748599a7fb0bfa1022b56'

         },success:function(res){//成功执行的函数

                            console.log("成功的执行:")

                            console.log(res)

         },

         fail:function(res){//失败执行的函数

                   console.log("失败的执行:")

                   console.log(res)

         },

         complete:function(res){//不管成功失败都会执行的函数

                            console.log("complete的执行:")

                            console.log(res)

         }

})

})

 

转载于:https://www.cnblogs.com/ruckly/p/11006744.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值