关于数据请求 Ajax

1.原生的ajax
window.onload = function(){
// 1.创建XMLHttpRequest   判断语句是为了兼容更多的浏览器
var xmlhttp = {};
if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest()      //ie7以后的版本
}else{
    xmlhttp = new ActiveXObiect("Microsoft.XMLHTTP")    //ie7以前的版本
}
console.log("第一步的状态" + xmlhttp.readyState)


// 2.设置请求   发送请求的方法(open / send)   
// open 方法:  语法:(请求类型,请求地址,异步/同步)
//              请求类型:GET 或 POST
//              请求地址:文件在服务器上的位置
//              异步/同步: 对应的值是 true / false  、不写的话默认是true(异步)  
// send 方法:  send(string)      string:仅用于 POST 请求

xmlhttp.open('get','https://bird.ioliu.cn/joke/rand?type=text',true)  //get、异步请求
console.log("第二步的状态" + xmlhttp.readyState)


// 3.发送请求 
xmlhttp.send();
console.log("第三步的状态" + xmlhttp.readyState)


// 4.回调函数
xmlhttp.onreadystatechange = function(){
    console.log("第四步的状态" + xmlhttp.readyState)

    if(xmlhttp.readyState == 4 && xmlhttp.status ==200){
        console.log(xmlhttp.responseText)
    }else{
        console.log("!!!!仔细检查代码!!!!")
    }
}

}
2.使用jquery写的一个ajax
$(function(){
    $("#btn").click(function(){
        $.ajax({
            url:"https://bird.ioliu.cn/joke/rand?type=text",     //请求地址
            type:"get",                         //请求方式
            dataType:"json",                    //返回数据类型    xml、html、script、json、jsonp、text
            // data:{   }   请求参数
            success:function(value){            //成功后的回调函数
                console.log(value);
                console.log("数据请求成功");
                $('#app').html(value)
            },
            error:function(){                   //失败后的回调函数
                console.log("数据请求失败")
            }
        })
    })
})
3.关于解决跨域的问题 jsonp

需要先使用script标签把需要的数据链接引入

html代码:
    <script src="http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=weather&code=101010100"></script>
js代码:
function weather(value) {
    console.log(value)
}
4.使用jquery写出 jsonp 解决跨域问题
$(function(){
 $.ajax({
     type:"post",       //请求方式
     async: true,       //异步?同步?
     url:"http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&code=101010100",   //请求的数据地址
     dataType:"jsonp",
     jsonp:"_jsonp",
     jsonpCallback:"wang",
     success:function(json){
         console.log(json)
     },
     error:function(){
         console.log("请求数据错误")
     }
 })
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值