使用js 原生的 XMLHttpRequest 發(fā)送get post 請(qǐng)求
2、使用xhr發(fā)起GET請(qǐng)求
四個(gè)步驟:
①:創(chuàng)建 xhr對(duì)象
//1、創(chuàng)建一個(gè) xhr 的對(duì)象
let xhr = new XMLHttpRequest()
②:調(diào)用 xhr的open()函數(shù)(open中傳遞兩個(gè)參數(shù),參數(shù)一是GET/POST請(qǐng)求方式,參數(shù)二是請(qǐng)求的URL地址)
//2、調(diào)用xhr中的open()函數(shù),創(chuàng)建一個(gè)Ajax的請(qǐng)求
xhr.open('GET', 'http://www.baidu.com')
③:調(diào)用 xhr.send()函數(shù)
//3、調(diào)用xhr的send函數(shù),發(fā)起請(qǐng)求
xhr.send()
④:監(jiān)聽(tīng) xhr.onreadystatechange事件
//4、監(jiān)聽(tīng) onreadystatechange 事件
xhr.onreadystatechange = function () {
//固定寫法
if (xhr.readyState === 4 && xhr.status === 200) {
//數(shù)據(jù)獲取成功,獲取服務(wù)器響應(yīng)的數(shù)據(jù)
// xhr.response 是返回一個(gè)請(qǐng)求對(duì)象,responseText是把返回體以string方式輸出
console.log(xhr.responseText)
}
}
xhr發(fā)起GET請(qǐng)求的完整代碼
<script>
// 攜帶參數(shù)
let param = 1;
let url = http://www.baidu.com
//1、創(chuàng)建一個(gè) xhr 的對(duì)象
let xhr = new XMLHttpRequest()
//2、調(diào)用xhr中的open()函數(shù),創(chuàng)建一個(gè)Ajax的請(qǐng)求,拼接請(qǐng)求參數(shù)
xhr.open('GET',url+'?param='+param)
//3、調(diào)用xhr的send函數(shù),發(fā)起請(qǐng)求
xhr.send()
//4、監(jiān)聽(tīng) onreadystatechange 事件
xhr.onreadystatechange = function () {
//固定寫法
if (xhr.readyState === 4 && xhr.status === 200) {
//數(shù)據(jù)獲取成功,獲取服務(wù)器響應(yīng)的數(shù)據(jù)
console.log(xhr.responseText)
}
}
</script>
發(fā)送post請(qǐng)求
直接上示例文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-586973.html
function httpPostLocaltion(key,params){
let url = "http://www.baidu.com";
// 把參數(shù)對(duì)象轉(zhuǎn)換為json
let param = JSON.stringify(params);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status === 200) {
console.log("后端返回的結(jié)果:"+this.responseText);
/** 你的邏輯代碼 **/
this.response
console.log(this.response)
}
};
xhr.open(
"post",
url,
true
);
// 注意,設(shè)置請(qǐng)求頭的信息必須寫在下面,否則會(huì)報(bào)錯(cuò)
// 設(shè)置以json傳參
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 解決跨域問(wèn)題
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
// 設(shè)置請(qǐng)求體攜帶的參數(shù)
xhr.send(param);
}
報(bào)錯(cuò)內(nèi)容是這個(gè)
Failed to execute ‘setRequestHeader’ on ‘XMLHttpRequest’: The object’s state
那就是上面提出的問(wèn)題,需要把設(shè)置請(qǐng)求頭的信息放到監(jiān)聽(tīng)方法下方文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-586973.html
到了這里,關(guān)于原生js XMLHttpRequest發(fā)送 get post 請(qǐng)求 解決跨域 及 注意事項(xiàng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!