我这里有一个小问题。我想从PHP foreach循环调用Ajax函数下面是我的代码:
Ajax: 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 and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var bla = document.getElementById('bla').value;
var queryString = "?bla=" + bla;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
和php代码:
foreach ($data AS $key => $value){
<form name="myForm">
<input type="text" id="bla" name="bla" value="<?php echo $value['bla']; ?>">
<input type="button" onclick="ajaxFunction(<?php echo $value['id']; ?>)" value="Speichern">
</form>
}
问题:当我单击foreach循环中生成的几个按钮时,只有foreach循环的第一个结果出现在输出中。我认为我必须提交个人ID从foreach循环(从数据库)到Ajax函数,但我不知道如何做到这一点。
可以这样调用函数吗?函数ajaxFunction(id) ?
在PHP foreach循环中,为每个文本输入分配相同的ID。当你调用getElementById()时,它将总是返回DOM中具有该ID的第一个元素,并且变量"bla"将被赋予第一个元素的value属性。
它看起来像你可能已经试图在一个ID传递到ajaxFunction调用在onclick属性,所以也许你可以做以下:
1)在文本输入的id属性中放置相同的echo语句。
<input type="text" id="<?php echo $value['id']; ?>" name="bla" value="<?php echo $value['bla']; ?>">
2)添加一个参数ajaxFunction定义。
function ajaxFunction(requestedID){
3)并将该变量传递给getElementById调用。
var bla = document.getElementById(requestedID).value;