douchi0028 2014-08-19 13:57
浏览 38
已采纳

如何从提交的do ... while表单中获取值

I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:

SS of the GUI

But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.

The code is as follow:

<script>
function submitForm() {
    $.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
    $('#myJobs_Right').find('.form_result').html(response);
    }});

    return false;
}
</script>

</head>

<body>

<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
  <form id="MyJobsForm"  onsubmit="return submitForm();">
    <?php do { ?>
      <input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
      <input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
      <br/>
      <br/>
      <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
  </form>
</li>
</ul>

<div id="myJobs_Right">
 <div class="form_result"> </div>
</div>

</body>

The jQuery-ajax-demo.php page looks like this:

<?php
if(isset($_POST['name'])) {
    $name = $_POST['name'];

    ?>
    Your Name Is: <?php echo $name; ?><br />
    <?php
    die();
}
?>
  • 写回答

1条回答 默认 最新

  • douzhao6584 2014-08-19 14:08
    关注

    If you have to do it this way, then you might try creating a new form for each button:

    <?php do { ?>
      <form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
          <input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
          <input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
          <br/>
          <br/>
      </form>
    <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
    

    Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:

    function submitForm(form) {
        var $form = $(form);
        $.ajax({
            type:'POST', 
            url: 'jQuery-ajax-demo.php', 
            data:$form.serialize(), 
            success: function(response) {
                $('#myJobs_Right').find('.form_result').html(response);
            }
        });
    
        return false;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀