js使用XMLHttpRequest()向php发送请求,接收php的echo值
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>form提交</title>
<script>
function f1() {
var request=new XMLHttpRequest();//建立request请求
request.open('post','boke.php');//发送对象是boke.php 发送post
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//请求头 默认即可
var name=form1.name.value;//获取文本框内输入的内容
request.send("name="+name);//发送request请求 请求可以有多个post 格式:key1=value1&key2=value2 php端根据key取出value
//确认接收消息
request.onreadystatechange=function () {
// readyState=4为php收到并返回值 status为返回字段为200火304
if(request.readyState==4&&(request.status==200||request.status==304)){
//弹出窗口显示php返回的值
alert(request.responseText);
}
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="name">
<!-- 点击按钮调用js的f1方法-->
<input type="submit" onclick="f1()">
</form>
</body>
</html>
boke.php
<?php
if(isset($_POST['name']))
echo "接收到name".$_POST['name'];
else
echo "未接收到name";