最近學習了ajax,記錄一下學習寫過的代碼和一些問題
一、原生ajax
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("get",url,true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState ==4 && xhr.status == 200) {
var responseText = JSON.parse(xhr.responseText);
if(responseText.status == 0) {
}
}
說明:
1.responseXML是一個對象,可以調用對象的api解析,而responseText是字符串要用var data= JSON.parse(str)將字符串轉化為json對象
2.JSON.stringify(data);將json對象轉化為字符串
3.如果提交方式改為post,需要使用xhr來模仿表單提交,具體方法為:設置xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
4.解決緩存問題:在url后面傳參時傳入當前的毫秒數 (new Date()).getTime()
如:http://cdn.weather.hao.360.cn/sed_api_area_query.php?grade=town&_jsonp=loadTown&code=0101&_=1477837767684&_="+(new Date()).getTime();
二、通過xhr實現ajax通信的一個限制來源於跨域安全策略,解決方案:jsonp
function handleResponse(response){
console.log(response.ip+response.name);
}
var script = document.createElement("script");
script.src="http://freegeoip.net/json?callback=handleResponse"
document.head.appendChild(script);
ajax在jquery中的用法
&.ajax({
type:"post",
url:"./jsonp.php?username=username",
dataType:"html",
data:{username:"qqq",password:"123"}.兩種方式都可以這樣傳
success: function(json){//success就是回調函數,解析數據就是這
console.log(json);
},
error:function(){
console.log("fail");
}
})
說明:
data選項既可以包含一個查詢字符串,比如 key1=value1&key2=value2 ,也可以是一個映射,比如 {key1: 'value1', key2: 'value2'} 。如果使用了后者的形式,則數據再發送器會被轉換成查詢字符串。
jsonp在jquery里的用法:
&.ajax({
type:"get",
async:true,//異步標志位
url:url,
dataType:"jsonp",
data:{username:"qqq",password:"123"},
jsonp:"cb",//傳遞給請求處理程序或頁面的,用以獲得jsonp回調函數名的參數名(默認為:callback)
jsonpCallback:"callback",//自定義的jsonp回調函數名,默認為jQuery自動生成的隨機函數名(類似:jQuery110201451414_4323443(["zhangsan","lise"]))
success: function(json){//success就是回調函數,解析數據就在這
//console.log(json);
}
error:function(){
console.log("fail");
}
})
