这是我的测试页:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
var test = "Hallo Welt";
$.ajax({
url: "ajax.php",
type: "post",
data: {
test: test
},
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
});
</script>
</head>
<body>
<form>
<input type="button" id="button" value="Test" style="width:200x">
</form>
<?php
if(isset($_POST["test"])) {
echo $_POST["test"];
}
?>
</body>
</html>
有没有人有提示?
问候
最佳答案
您不需要单独的 PHP 文件来处理 AJAX 请求,尽管这样做会有好处。如果您有一个单独的文件,假设名为“data.php”,您可以以这种方式设置该脚本,以便它可以处理许多不同的请求 - 每次调用您的 ajax 函数时,url 都是相同的(data.php
) 但请求中发送的参数会改变。
下面的 exit
语句仅在 POST
请求中遇到,并阻止将剩余的 html 发送回您的 javascript 回调函数。
<?php
/* Intercept the POST request, do whatever processing required and echo a response */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* Remove any previous output from our reply */
ob_clean();
/* send the response */
if( isset( $_POST["test"] ) ) echo $_POST["test"];
/* The `exit` statement prevents the rest of the page being sent in response */
exit();
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
var test = "Hallo Welt";
$.ajax({
url: "ajax.php",
type: "post",
data: {
test: test
},
success: function (response) {
alert(response);
document.getElementById('out').innerHTML=response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
});
</script>
</head>
<body>
<form>
<input type="button" id="button" value="Test" style="width:200x">
<output id='out'></output>
</form>
</body>
</html>
关于javascript - Ajax 响应整个页面代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119707/