1. 程式人生 > >ajax與jsonp

ajax與jsonp

數據 and llb 狀態 else == chan element ota

    var xhr = new XMLHttpRequest()
    
    xhr.onreadystatechange = function(){//狀態觸發事件
        if(xhr.readyState == 4){
            if(xhr.status >=200 && xhr.status<300 || xhr.status == 304){
                console.log(xhr)
            }else{
                console.log(xhr.status)
            }
        }
    }
    xhr.onprogress 
= function(event){//瀏覽器接受新數據期間周期性觸發 if(event.lengthComputable){ console.log(event.total) } } xhr.open(‘get‘,‘data/cart.json‘,true); xhr.setRequestHeader(‘myheader‘,‘myvalue‘)//可以設置自定義頭部信息 xhr.send(null)//接收一個參數,即要作為請求主體發送的數據,若無,為了瀏覽器兼容,必須傳入null。 //
跨域jsonp function handleResponse(response){ console.log(response.ip,response.city,response.region_name) } var script = document.createElement(‘script‘) //script和img一樣有能力不受限制從其他域加載資源 script.src = ‘http://freegeoip.net/json/?callback=handleResponse‘; document.body.insertBefore(script,document.body.firstChild)

ajax與jsonp