我有一些嵌入在 php while 循环中的表单,并且它是由 javascript 通过 getelementbyid 处理的,每当我提交时,它只会提交循环上的第一个表单项。下面是我的 php
$qsel = "SELECT * FROM sellbusiness ORDER BY sn DESC LIMIT 2";
$results = mysqli_query($conn,$qsel) or die(mysqli_error());
$num_rows = mysqli_num_rows($results);
while($rows=mysqli_fetch_array($results)){
$status = $rows['status'];
$usern = $rows['username'];
$video = $rows['video'];
?>
<input type="text" id="usercomment" value=" " name="comment" placeholder="Enter your comment" class="form-control" />
<input type="hidden" name="postcode" id="postcode" value="<?php echo $postcodez; ?>" class="form-control" />
<input type="hidden" name="username" id="username" value="<?php echo $usern; ?>" class="form-control" />
<input type="hidden" name="commentor" id="commentor" value="<?php echo $username; ?>" class="form-control" />
<span class="input-group-btn">
<button type="button" id="submit" onclick="myComment()" class="btn btn-primary btn-xs pull-right " >Post Comment!!!!</button>
<?php } ?>
下面是我的ajax
<script type="text/javascript">
function myComment() {
var usercomment= document.getElementById("usercomment").value;
var commentor= document.getElementById("commentor").value;
var postcode = document.getElementById("postcode").value;
var username = document.getElementById("username").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'usercomment1=' + usercomment + '&commentor1=' + commentor + '&postcode1=' + postcode + '&username1=' + username ;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "commenthandler.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
return false;
}
</script>
最佳答案
哇,这有很多问题,特别是从编程的 Angular 来看。你没有正确利用 jQuery 提供的框架,就像你借用了它的 AJAX 功能,但你坚持使用困难的传统 JavaScript 来完成其他所有事情。 jQuery 最擅长的事情之一就是选择元素。不要将输入字段的值串在一起,而是使用(错误地)getElementById()
,使用 jQuery 函数 .serialize()
对表单中的全部数据进行编码。如果这样做,则不需要添加不必要的 id
到您的输入字段。
我会尽力提供帮助,以便您能找到有用的东西。
$(document).ready(function() {
$("#submit").click(function() {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "commenthandler.php",
data: $("form").serialize(),
cache: false,
success: function(html) {
alert(html);
}
});
});
});
您可以删除 onclick
来自您的 <button>
的属性,因为 jQuery 能够将函数绑定(bind)到按钮的单击。您可以继续使用$_POST['usercomment']
, $_POST['postcode']
从你的 PHP 内部等等。但是,重要的是要认识到,即使您可以很好地使用 jQuery,getElementById()
不返回单个元素,它返回元素的数组。这就是为什么这行不通的原因:
var usercomment= document.getElementById("usercomment").value;
var commentor= document.getElementById("commentor").value;
您没有指定 ID 为 usercomment
的哪个元素从中获取值(value)。如果您要使用getElementById()
对于某些东西,您必须指定要使用数组的哪个元素,如下所示。
var usercomment = document.getElementById("usercomment")[0].value;
var commentor = document.getElementById("commentor")[0].value;
您还缺少结束语 <span>
示例中的标记。
关于javascript - getelementbyid 仅适用于 php while 循环中的第一个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543229/