關於數據請求 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("請求數據錯誤")
     }
 })
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章