时间:2022-01-20加入收藏
<html>
<head>
<title>json</title>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
json
<input type="button" onclick="sendJson()" value="点击">
</body>
<script>
function sendJson() {
var stu={
name:"你的名字",
age:18,
sex:"男"
};
$.ajax({
type : "POST", //提交方式
url : "http://localhost/jsonTest.php",//路径,www根目录下
data : {
"student" : stu
},//数据,这里使用的是Json格式进行传输
success : function(result) {//返回数据根据结果进行相应的处理
alert(result);
}
});
}
</script>
</html>
以上是在同一个域名下(同服务器)的情况,如果两个域名(包括子域名跟主域名都算跨域)就涉及到跨域的问题,html部分需要修改url,php的代码需要加允许跨域<?php
$student = $_POST['student'];
echo $student['name'];
echo $student['age'];
echo $student['sex'];
?>
php代码<html>
<head>
<title>json</title>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
json
<input type="button" onclick="sendJson()" value="点击">
</body>
<script>
function sendJson() {
var stu={
name:"你的名字",
age:18,
sex:"男"
};
$.ajax({
type : "POST", //提交方式
url : "http://211.83.247.14/TempServer/jsonTest.php",//注意!这个是跟上面不一样的地方
data : {
"student" : stu
},//数据,这里使用的是Json格式进行传输
success : function(result) {//返回数据根据结果进行相应的处理
alert(result);
}
});
}
</script>
</html>
这样html那边访问后就会alert出echo的信息<?php
header('Access-Control-Allow-Origin:*');//注意!跨域要加这个头 上面那个没有
$student = $_POST['student'];
echo $student['name'];
echo $student['age'];
echo $student['sex'];
?>