我想发布带有ajax的简单表单并更新div的内容(id结果),但我被重定向到server.php文件。
的index.php:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/ajax.js" type="text/javascript"></script>
<form id="wbForm" action="server.php" method="POST">
Date1: <input type="text" name="date1" value="2000-01-21"><br>
Date2: <input type="text" name="date2" value="2000-01-02"><br>
<input type="submit" name="submit" value="Submit">
<div id="result"></div>
</form>
</body>
</html>
ajax.js:
$(document).ready(function showHint(form) {
$.ajax({
type:'POST',
url: 'server.php',
data:$('#wbForm').serialize(),
success: function(response) {
$('#wbForm').find('.result').html(response);
}});
});
server.php:
<?php
$input=$_POST;
//... compute something
echo "result";
?>
字符串&#34;结果&#34;应该出现在id = result的div中,但是我被重定向到/server.php,在那里我可以看到&#34;结果&#34;,为什么?
答案 0 :(得分:0)
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/ajax.js" type="text/javascript"></script>
<form id="wbForm" action="server.php" method="POST">
Date1: <input type="text" name="date1" value="2000-01-21"><br>
Date2: <input type="text" name="date2" value="2000-01-02"><br>
<input type="submit" name="submit" value="Submit">
<div id="result"></div>
</form>
</body>
</html>
ajax.php
$(document).on("ready", function(){
//Form action
$("#wbForm").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'server.php',
data:$('#wbForm').serialize(),
success: function(response) {
$('#wbForm').find('.result').html(response);
}});
});
});
server.php
<?php
$input = $_POST;
print_r( $input );
?>
快乐的Codding !!
答案 1 :(得分:0)
有几个问题。首先,当您点击提交时,由于您的表单操作&#34; server.php&#34;,您将被重定向到server.php。如果您希望在单击按钮时发生AJAX调用,则应将AJAX调用放在JavaScript函数中并调用该函数onclick()
jQuery .AJAX调用没有触发成功的原因是因为它期待JSON。尝试:
<?php
header("content-type:application/json");
$input=$_POST;
//... compute something
echo json_encode("result");
?>
希望这有帮助。