【发布时间】:2015-04-20 22:58:10
【问题描述】:
我有一个 php 脚本,它从数据库中获取项目并允许用户为它们投票,我给每个获取的项目一个(html 表单),其中一个(输入文本字段)和一个(提交按钮)提交单击时输入分数,并且我在同一页面中有一个 jQuery 脚本,该脚本通过该表单将分数插入数据库而不刷新页面,除了脚本有一个之外,一切似乎都工作得很好。
这个脚本只允许提交循环中的第一个(html 表单),而这个第一个(html 表单)会影响循环中不跟随它的项目,如何使每个表单都归因于它的项目?
除此之外,我还希望脚本为提交分数的用户返回通知,以通知他们数据是成功插入还是失败,以及当成功时,我希望用户提交的分数在提交
感谢任何帮助,这是我的代码:
<body>
<div id="items-wrapper">
<?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
<div id="item">
<?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
<ul id="responds">
<!--i want to append data here-->
</ul>
<img src="<?php echo $item_file; ?>" />
<form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
<input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
<button id="FormSubmit">Add Score</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</form>
<?php } ?>
</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Ajax request to setItemScore.php
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#contentText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var myData = 'score_value=' + $("#contentText").val();
jQuery.ajax({
type: "POST",
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
dataType: "text",
data: myData,
success: function(response) {
$("#responds").append(response);
$("#contentText").val('');
$("#FormSubmit").show();
$("#LoadingImage").hide();
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
</script>
</body>
【问题讨论】:
-
两件事:-确保您的 ID 是唯一的-默认情况下,按钮 html 是“type=submit”,所以输入“type=button”
-
我通过表单操作传递的 id 肯定是独一无二的!!
-
Id 在页面中必须是唯一的,如果一个元素必须出现多次,则使用该类。所以将 id="FormSubmit" 更改为 class="FormSubmit" 并更改您的侦听器
-
好点,但问题仍然存在!