我正在尝试的是使用javascript从我的php页面获取数据,但似乎javascript无法正常工作。在此单击我的提交按钮时,数据应该被发送到操作页面,但我不想要转到php页面,php页面中的结果应显示在初始页面中(在div id:result中)
页面视图 enter image description here
这是我的索引页面,这只是示例视图
register.html
<!DOCTYPE>
<html>
<head>
<title>REGESITER</title>
<script src="script/jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
$("sub").click( function() {
$.post($("#myform").attr("action"),
$("#myform :input").serializeArray(),
function (data) {
$("#res").empty();
$("#res").html(data);
});
$("#myform").submit( function() {
return false;
});
});</script>
</head>
<body>
<form id="myform" action="helper.php" method="post">
FIRSTNAME:<input type="text" name="txtfname" id="fname">
<br><br>
LASTNAME:<input type="text" name="txtlname" id="lname">
<br><br>
AGE:<input type="text" name="txtage" id="age">
<br><br>
<button id="sub">SUBMIT</button>
</form>
<div id="res">Result</div>
</body>
</html>
这是我的php文件,从中获取回显结果
helper.php
<?
$fname=$_POST['txtfname'];
$lname=$_POST['txtlname'];
$age=$_POST['txtage'];
$con=mysql_connect('localhost','root','');
if ($con)
{
$db=mysql_select_db('register',$con);
}
if ($db)
{
$q1=mysql_query("insert into regdb(firstname,lastname,age) values('$fname','$lname','$age')",$con);
echo"inserted into database";
}
else
{
echo "error in query";
}
?>
答案 0 :(得分:1)
完整的工作HTML代码: -
<!DOCTYPE>
<html>
<head>
<title>REGESITER</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$( document ).ready(function() {
$( "#sub" ).click(function(event) {
$.post('helper.php',
$("#myform :input").serializeArray(),
function (data) {
$("#res").empty();
$("#res").html(data);
});
});
});
</script>
</head>
<body>
<form id="myform" action="" method="post">
FIRSTNAME:<input type="text" name="txtfname" id="fname">
<br><br>
LASTNAME:<input type="text" name="txtlname" id="lname">
<br><br>
AGE:<input type="text" name="txtage" id="age">
<br><br>
<input type="button" id="sub" value="Enter" />
</form>
<div id="res">Result</div>
</body>
</html>