我遇到了jQuery(或者php)的问题。我希望提交表单而不刷新页面,所以我最终得到以下代码,但问题是它不起作用。这是代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#submit").click(function() {
var name = $("#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "p.php",
data: dataString,
success: function(){
alert("It works");
}
});
return false;
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
<br />
</body>
</html>
处理页面:
<?php include("../includes/includes.php"); ?>
<?php $name = $_POST['name']; ?>
<?php $sql = "INSERT INTO xyz
(id, value) VALUES
(1, '{$name}')";
$result = $database->query($sql);
?>
答案 0 :(得分:4)
我不知道为什么它不起作用,但你可以尝试这样
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" />//change type to button
</p>
</form>
也会发出错误回调
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val();
$.ajax({
type: "POST",
url: "p.php",
data: {name:name},
success: function(){
alert("It works");
},
error:function(e){alert("it failed");}
});
});
});
答案 1 :(得分:1)
您需要像这样修改表单标记:
<form id="myForm" name="myForm" action="" onsubmit="return false;">