更新時間:2021-12-01 09:41:56 來源:動力節點 瀏覽1398次
Ajax傳值的方式只有兩種:GET 和 POST方式
GET:
xmlhttp = new XMLHttpRequest();
//異步執行函數
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","target.php?tid=1",true);
xmlhttp.send();
//open里面函數值分別是“傳值方式”、“目標網頁”、“是否異步”,send中不用寫任何東西
POST:
xmlhttp = new XMLHttpRequest();
//異步執行函數
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","target.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("user_id="+getCookie("user_id")+"&"+"user_pwd="+getCookie("user_pwd"));
1.POST第二行要設置響應頭,固定的!!!!!!
2.POST發送的數據用&隔開,千萬不能用錯,雖然傳送的是cookie值,但并不是直接將cookie寫上去(cookie是用分號隔開)
3.在服務器那邊的php直接就能用$_POST["user_id"]來獲取數據(好久才跳出來的坑)
4.xmlhttp.onreadystatechange()函數是異步執行的,要等到服務器返回了數據才執行,所以書寫在哪里都行,使用該函數的前提是“是否異步”為true
5.如果“是否異步”為false,則需要將xmlhttp.onreadystatechange()函數寫在xmlhttp.send()后面
通過上述介紹相信大家對Ajax傳值的方式已經有所了解,如果小伙伴對此比較感興趣,想了解更多相關知識,不妨來關注一下動力節點的Ajax視頻教程,里面的內容由淺到深,通俗易懂,很適合沒有基礎的朋友學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習