原生js的ajax數據請求
注:原生的ajax請求.在發送post請求的時候,
請求的Content-Type爲text/plain;charset=UTF-8,而請求參數在Request Payload中。
如果是使用jq發送post請求,參數在Form Data
這裏要注意post請求的Content-Type爲application/x-www-form-urlencoded,參數是在請求體中,即上面請求中的Form Data。
最後查閱文檔才知道,
HTTP POST表單請求提交時,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST請求如果不指定請求頭RequestHeader,默認使用的Content-Type是text/plain;charset=UTF-8。
也就是解決這個問題就是要求設置請求頭
//手機號綁定
function apply(){
var XHR=null;
if (window.XMLHttpRequest) {
// 非IE內核
XHR = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE內核,這裏早期IE的版本寫法不同,具體可以查詢下
XHR = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XHR = null;
}
if(XHR){
var code = document.getElementById("numcode").value
var mobile=document.getElementById("num").value
var postdata="mobile="+mobile+"&code="+code
XHR.open("POST", "/ajax/json/live/dosignup");
XHR.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XHR.onreadystatechange = function () {
if (XHR.readyState == 4 && XHR.status == 200) {
var mydata =JSON.parse(XHR.responseText);
console.log(mydata)
if(mydata.code){
document.getElementById("codeerr").style.display='block'
document.getElementById("msgcode").innerText=mydata.msg
}else{
$('.zao').css('display','none')
location.reload()
}
XHR = null;
}
};
XHR.send(postdata);
}
}