<button id=”button”>获取php数据</button>
<br><br>
<h1>正常表单get提交数据到php</h1>
<form action=”process.php” method=”get”>
<input type=”text” name=”name”>
<input type=”submit” value=”提交”>
</form>
<h1>ajax请求数据get</h1>
<form id=”getForm”>
<input type=”text” name=”name” id=”name1″>
<input type=”submit” value=”提交”>
</form>
<h1>正常表单post提交数据到php</h1>
<form action=”process.php” method=”post”>
<input type=”text” name=”name”>
<input type=”submit” value=”提交”>
</form>
<h1>ajax请求数据post</h1>
<form id=”postForm”>
<input type=”text” name=”name” id=”name2″>
<input type=”submit” value=”提交”>
</form>
<script>
document.getElementById(‘button’).addEventListener(“click”,GetData);
document.getElementById(‘getForm’).addEventListener(“submit”,GetForm);
document.getElementById(‘postForm’).addEventListener(“submit”,postForm);
function GetData(){
var xhr=new XMLHttpRequest();
xhr.open(“GET”,”process.php?name=aa”,true);
xhr.onload=function(){
console.log(this.responseText);
}
xhr.send();
}
function GetForm(e){
e.preventDefault();
var name=document.getElementById(“name1”).value;
var xhr=new XMLHttpRequest();
xhr.open(“GET”,”process.php?name=”+name,true);
xhr.onload=function(){
console.log(this.responseText);
}
xhr.send();
}
function postForm(e){
e.preventDefault();
var name=document.getElementById(“name2”).value;
var xhr=new XMLHttpRequest();
var params=”name=”+name;
xhr.open(“POST”,”process.php”,true);
// 设置请求头
xhr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
xhr.onload=function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
php页面:
<?php
// echo “hello world”;
if(isset($_GET[‘name’])){
echo “GET:你的名字是”.$_GET[‘name’];
}
if(isset($_POST[‘name’])){
echo “POST:你的名字是”.$_POST[‘name’];
}
?>