我正在做ajax函数,使用表单和输入类型=隐藏插入数据库,但是当我在同一页面中放置多个表单时,它总是只取第一个表单中的第一个值
这是代码:
Ajax 函数
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var in1 = document.getElementById("in1").value;
var queryString1 = "?in1=" + in1;
//ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString1, true);
ajaxRequest.send(null);
}
//–>
</script>
这是 HTML 表单
<form name="myForm1">
<input type="hidden" value="1" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm2">
<input type="hidden" value="2" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm3">
<input type="hidden" value="3" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
</form>
</form>
</form>
这是执行数据库查询的检查.php代码
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","admin","123456") or die('Cannot connect to the database
because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("dbname") or die("Unable to select database");
//select which database we're using
// Retrieve data from Query String
$in1 = $_GET['in1'];
// Escape User Input to help prevent SQL Injection
$in1 = mysql_real_escape_string($in1);
//Build and run a SQL Query on our MySQL tutorial
if($in1){
mysql_query("INSERT INTO test (name)
VALUES ('" . $in1. "')");
}
?>
当我单击任何链接时,它总是发送第一个值。
呃,有人告诉我这里有什么问题吗?
id
值在页面上必须是唯一的。您已经证明您有多个具有相同id
值 ( "in1"
) 的input type="hidden"
元素。如果您有多个具有相同id
值的元素,当您尝试查找它时(例如,使用 getElementById
),大多数浏览器会为您提供第一个,但这是未定义的行为,因为标记/DOM 无效。
解决方法是修复 ID,使它们是唯一的,或者根本不使用 ID 并使用不需要唯一的东西,例如 name
或 class
- 但随后您需要使用 querySelectorAll
或类似内容检索它,并处理您有多个匹配元素的事实。