jQuery傳送ajax請求,PHP響應ajax請求(含跨域)
阿新 • • 發佈:2019-01-27
不跨域:
echo.html
<!doctype html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<title> ajax test</title>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
</head>
<body>
<p id="post1">info 1</p>
<p id="post2">info 2</p>
<input type="button" id="btn" value="click"></input>
<script type="text/javascript">
$("#btn").click(function(){
$("#click").text("is click");
$.ajax({
url:'./api.php',
type:'post',
dataType:'json',
data:{ post1:"post1", post2:"post2"},
success:function(data){
$("#post1").text(data[0]);
$("#post2").text(data[1]);
},
error:function(data){
alert("ajax error:"+data);
},
});
});
</script>
</body>
</html>
api.php
<?php
$post1=$_POST['post1'];
$post2=$_POST['post2'];
$post1=$post1."+echo2";
$post2=$post2."+echo2";
$array=array($post1, $post2);
echo json_encode($array);
?>
跨域請求:
echo.html
<!doctype html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<title> ajax test</title>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
</head>
<body>
<p id="post1">info 1</p>
<p id="post2">info 2</p>
<input type="button" id="btn" value="click"></input>
<script type="text/javascript">
$("#btn").click(function(){
$("#click").text("is click");
$.ajax({
url:'http://192.168.0.100/api.php',
type:'post',
dataType:'json',
data:{ post1:"post1", post2:"post2"},
success:function(data){
$("#post1").text(data[0]);
$("#post2").text(data[1]);
},
error:function(data){
alert("ajax error:"+data);
},
});
});
</script>
</body>
</html>
另外一臺電腦(192.168.0.100)上的
api.php
<?php
header("Access-Control-Allow-Origin:*");
$post1=$_POST['post1'];
$post2=$_POST['post2'];
$post1=$post1."+echo2";
$post2=$post2."+echo2";
$array=array($post1, $post2);
echo json_encode($array);
?>