一、连接检测(WampServer3.0以上)
如图打开httpd-vhosts.conf配置文件,DocumentRoot和Directory设为php文件所在路径,Require all granted;
例:
重启wamp,在需要发送请求的主机上打开浏览器,地址栏输入http://192.168.2.80/panda.php(地址根据实际情况修改),返回相应数据表示连接成功。
二、AJAX发送请求
//虽然GET方法简单可行,但当传送数据量超过URL承载量的时候一般采用POST方法
function() {
//创建XMLHttpRequest对象与服务器进行交互
var xmlhttp = new XMLHttpRequest;
//onreadystatechange事件规定当服务器响应已做好被处理的准备时所执行的任务
xmlhttp.onreadystatechange=function() {
//readyState==4 && status==200表示请求已完成,且响应已就绪;
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//responseText表示获得字符串形式的响应数据;
var return_value = xmlhttp.responseText;
//浏览器控制台输出内容
console.log(return_value);
}
}
//以POST方式向指定URL发送请求,并异步获取数据(不等待,直接返回)
xmlhttp.open("post","http://192.168.2.80/panda.php",true);
//表示客户端提交给服务器文本内容的编码方式是URL编码
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//向PHP发送数据
xmlhttp.send("name=json&sex=male");
}
三、PHP接收返回数据
<?php
function post(){
//json头
header("Content-type: application/json");
//跨域
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin:*");
//CORS实现跨域访问
header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');
echo $_POST("name");
echo $_POST("sex");
}