我正在尝试使用表单将两个 javascript 变量提交到 php 脚本,并通过 ajax 函数将输出返回到同一页面上的新 Div。它不起作用。
这是我的代码
javascript/html
<link href="style/background.css" rel="stylesheet" type="text/css">
<script src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
fbPageOptions = {
shadowType: 'halo',
resizeDuration: 5.5,
imageFadeDuration: 4.5,
overlayFadeDuration: 0,
navType: 'both',
width: 580,
height: 405
};
</script>
<body>
<div id ="userForm">Add New User
<br>
<br>
<form id ="form">
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname" ><br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
<script type="text/javascript">
var firstname = "";
var lastname = "";
$('#form').submit(function() {
firstname = $("input#firstname").val();
lastname = $("input#lastname").val();
alert(firstname + lastname);
$.ajax({
type: "POST",
url: "my url is in here",
data: {firstname: firstname, lastname: lastname},
success: function(data) {
$("#submitted").html(data);
alert("success");
}
});
});
</script>
<br>
<div id="submitted"></div>
</body>
这是php代码
<?php
$firstname = $_POST["firstname"];
echo "First name added is $firstname";
echo "<br>";
$lastname = $_POST["lastname"];
echo "Last name added is $lastname";
?>
当我提交表单时,警报框会触发,但 div 未更新。我在另一个页面上使用几乎相同的代码,它工作正常。:( 有任何想法吗?
非常感谢。