js寫法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" name="">
</body>
</html>
<script>
document.querySelector("input").onclick=function(){
var xhr =new XMLHttpRequest(); //創建異步對象,這里的()別忘記了
xhr.open("post","xxx.php"); //設置請求行:請求的方式(post/get),請求的url (get:會在網址欄中出現結果,易於測試但安全性不高。post無這種問題)
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//請求頭,在post請求方式中必須有並且特定這種寫法
xhr.onreadystatechange=function(){ //回調函數,還有一種onload寫法 //xhr.onload=function(){}
if(this.readyState==4&&this.status==200){ //狀態等於4時響應完成,但頁面404時仍可接收到響應,所以這里要status(頁面狀態)==200,既頁面正常才給接收響應
console.log(this.readyState); //值是4
console.log(this.responseText);
}
};
xhr.send("name=heihei&skill=haha&age=15&sex=man");
//(請求主體)發送請求,post請求方式的請求信息寫在請求主體里,就是這里(這里已經寫了)
//get請求方式的請求信息寫在請求行里,如 xhr.open("get","xxx.php?name=heihei&skill=haha&age=15&sex=man")```
}
</script>
jQuery寫法
$(function(){
$("input").on("click",function(){
$.ajax({
url:"./callback.php", //請求地址
type:"get", //請求方式
data:"name=林子閑&wife=喬韻", //這里的data:發送給服務器的請求數據
success:function(data){ //回調函數:數據請求成功之后調用
console.log(data); //這里的data:從服務器發送回來的數據
},
// dataType:"json",
//dataType:"xml" 設置請求回來的數據格式是json還是xml.
//也可以在php文件里設置數據格式 header("content-type:application/json;charset=utf-8");
})
})
})