很棒的网站,出色的贡献者,我提前感谢您。
(咆哮)>72 小时,头发减少 50%,谷歌搜索“.ajax 简单示例”= 网络上没有简单、有效的示例 - :-)(/rant)
我正在从一个表单中收集数据,将该数据传递给一个 javascript 例程,该例程启动一个写入我的数据库的 php 文件。一切都很好 - 这是简单的工作脚本:
<script type="text/javascript">
$(document).ready(function(e) {
$("#submitbutton").click(function() {
var ln = 'DaVinci';
var fn = 'Leonardo';
$.ajax({
type: "POST",
url: "testbackendinsert.php",
data: {lastname: ln, firstname: fn}
})
.done( function( msg ) {alert( "Data Saved: " + msg );});
});
});
</script>
我可以将任何字符串放入 ln 和 fn 变量中,数据最终会出现在 db 中。
当我将表单放入(EASY,一个输入,一个按钮)时:
<form><table>
<tr><td>First Name</td><td><input type="text" id="fn" name="FirstName"></td></tr>
<tr><td colspan="2"><input type="submit" id="submitbutton" value="Submit" /></td></tr>
</table></form>
并使用这条线
var ln = document.getElementById("fn");
代替 var ln = "Somedudesname"; 它不起作用,或者崩溃(是的,崩溃,挂起)IE(我必须关闭并重新打开)。我已经尝试过 ("fn")、('fn')、(#fn)、('#fn')、("#fn") 并且不行。我敢肯定这是微不足道的(总是如此)-我错过了什么?
非常感谢!
这是整个代码:
HTML/JavaScript
<!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" />
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<title>test ajax frontend</title>
<style>
#divtest {
width:40%;
background-color:#C1C1FD;
text-align:left;
margin-left:auto;
margin-right:auto;
margin-top:5%;
font-size:16px;
line-height:16px;
border: 20px solid #FCD1E3;}
</style>
</head>
<body>
<div id="divtest">
<form>
<table>
<tr><td>First Name:</td><td><input type="text" id="fn" name="FirstName"></td></tr>
<tr><td>Last Name:</td><td><input type="text" id="ln" name="FirstName"></td></tr>
<tr><td>Zip code:</td><td><input type="text" id="zp" name="FirstName"></td></tr>
<tr><td colspan="2"><input type="submit" id="submitbutton" value="Submit" /></td></tr>
</table>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(e) {
$("#submitbutton").click(function() {
var ln = document.getElementById("ln").value;
var fn = document.getElementById("fn").value;
var zp = document.getElementById("zp").value;
$.ajax({
type: "POST",
url: "testbackendinsert.php",
data: {lastname: ln, firstname: fn, zip: zp}
})
.done( function( msg ) {alert( "Data Saved: " + msg );});
});
});
</script>
<!--
document.getElementById("fn")
document.getElementById("ln")
-->
</body>
这是写入数据库的 php:
<?php
echo "<title>Read db table.php</title>";
$ln = $_POST['lastname'];
$fn = $_POST['firstname'];
$z = $_POST['zip'];
$host = "name of host";
$user = "username";
$password = "password";
$dbname = "dbname";
$cxn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}
echo "connection made";
$query = "INSERT INTO testtable (lastname, firstname, zip) VALUES ('$ln', '$fn', '$z')";
$result = mysqli_query($cxn, $query) or die ("No query");
mysqli_close($cxn);
?>
祝大家编码愉快!再次感谢!