我正在使用ajax函数使用form和input type = hidden插入到DB中但是当我在同一页面中放入多个表单时,它总是只采用第一个表单中的第一个值
这是代码:
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>
这是执行数据库查询的check.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. "')");
}
?>
当我点击任何链接时,它总是发送第一个值。
有人告诉我这里的问题是什么?答案 0 :(得分:1)
id
值must be unique on the page。您已经证明您有多个input type="hidden"
个元素具有相同的id
值("in1"
)。如果您有多个具有相同id
值的元素,当您尝试查找它时(例如,使用getElementById
),大多数浏览器会给您第一个,但它是未定义的行为,因为标记/ DOM 无效。
修复方法是修复ID以使其唯一,或者根本不使用ID并使用不所需的内容,例如name
或class
- 但是您需要使用querySelectorAll
或类似内容检索它,并处理您有多个匹配元素的事实。