使用多个表单并停留在Ajax/php/jquery页面需要语法帮助


Using more than one form and staying on page with Ajax/php/jquery Syntax help required

尝试处理表单并保持在同一页面上。我的目标是能够点击照片下的按钮对它们进行分类。我将有100张照片在每个页面上,所以我宁愿只是能够点击周围,而不是有一个专门的页面为每张照片。跟着这里的一些线索,我就快到了。我只是需要一个正确的方向。我的代码工作,除了它读取所有三种形式,而不仅仅是我点击的一个。每个表单都有一个按钮,可以设置1、2或3个类别。无论我按下哪个按钮,它都会将类别更新为3。所以它漏出了表单,读取了所有的表单,最后一个是3,它将值更新为3。

任何帮助都非常感谢。

<!--(Header)-->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function() {
    $.ajax({
        type: 'POST',
        url: "test_ajax_update_code.php",
        data: $("FORM").serialize(),
    });
});
</script>
<!--(Body)-->
<img src="GLJ9988.jpg" width="500" height="333" border="0"><br>
<form>
    <input name="num" type="hidden" value="9988" >
    <input name="shw" type="hidden" value="1" >
    <input type="submit" value="1">
</form>&nbsp;&nbsp;&nbsp;
<form>
    <input name="num" type="hidden" value="9988" >
    <input name="shw" type="hidden" value="2" >
    <input type="submit" value="2">
</form>&nbsp;&nbsp;&nbsp;
<form>
    <input name="num" type="hidden" value="9988" >
    <input name="shw" type="hidden" value="3" >
    <input type="submit" value="3">
</form>

你不需要3个表单…1就足够了,只需编辑第一个表单,将第二个输入(name=shw)替换为选择框,并添加几行javascript(jQuery)

<form>
  <input name="num" value="9988">
  <button id="1">cat 1</button>
  <button id="2">cat 2</button>
  <button id="3">cat 3</button>
  <select name="shw" style="display:none;">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
</form>
<script type="text/javascript">
  $("form button").on("click",function(){
    var selected = $(this).attr("id");
    $("form").find("select").val(selected);  
    // ajax here
  });
</script>

为提交按钮绑定一个点击事件,并基于点击按钮表单触发ajax

$('input[type=submit]').on("click",function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: "test_ajax_update_code.php",
        data: $(this).parent().serialize(),
    });
})

$(this).parent()选择this之外的第一个元素在本例中是form元素

使用preventDefault防止页面刷新