【问题标题】:AJAX JSON loaded form buttons refreshes page instead on working with AJAX againAJAX JSON 加载的表单按钮刷新页面而不是再次使用 AJAX
【发布时间】:2018-08-01 19:12:43
【问题描述】:

我有一个奇怪的问题。我正在通过 AJAX 处理来自 while 循环内加载的表的数据,当成功处理数据时,该表将通过 AJAX 和 JSON 重新加载新数据。问题是,当新表被加载并且我再次从任何行单击相同的提交按钮时,这一次不是通过 AJAX 处理它,而是作为普通提交按钮工作并刷新页面。然后当页面刷新时,提交按钮再次通过 AJAX 工作。为什么在通过 AJAX 进行先前操作后通过 AJAX 重新加载表时,在两个表中使用的参数完全相同时,它不能与 AJAX 一起使用?我的代码如下。请告诉我这里出了什么问题以及解决方案是什么。

membership.php

<div class="row">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">Memberships List</h3>
        </div>
        <div class="card-body table-responsive p-0">
          <table class="table table-hover table-striped" id="mbslist">
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Daily Capping</th>
              <th>Commission</th>
              <th>Payout</th>
              <th>Payout %</th>
              <th>Cost</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
            <?php
              $i = 1;
              $mem = $pdo->prepare("SELECT * FROM memberships");
              $mem-> execute();
              while($m = $mem->fetch()){ extract($m);
                if($mem_status == 'enabled'){
                  $statusColor = "text-success";
                  $btn = "btn-danger";
                  $status = "disabled";
                  $btnVal = "Disable";
                }else{
                  $statusColor = "text-danger";
                  $btn = "btn-success";
                  $status = "enabled";
                  $btnVal = "Enable";
                }
            ?>
              <tr>
                <td><?php echo $i; ?></td>
                <td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
                <td>&#8377;<?php echo $mem_daily_capping; ?></td>
                <td>&#8377;<?php echo $mem_earn_amount; ?></td>
                <td>&#8377;<?php echo $mem_min_payout; ?></td>
                <td><?php echo $mem_payout_percent; ?>%</td>
                <td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "&#8377;$mem_price"; } ?></td>
                <td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
                <td>

                  <form method="post" action="">
                    <input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
                    <input type="hidden" value="<?php echo $status; ?>" class="status">
                    <input type="hidden" value="memstatus" class="type">
                    <?php if($mem_id != 1){ ?>
                      <input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
                    <?php } ?>
                    <a href="?mem=<?php echo $mem_id; ?>&action=edit" class="btn btn-primary">Edit</a>
                  </form>
                </td>
              </tr>
            <?php $i++; } ?>
          </table>
        </div>
      </div>
    </div>
    <div class="message"></div>
  </div>

AJAX 代码

// Set Membership Status
$(document).ready(function(){
    $(".mbslist").click(function() {
      var dataString = {
        id: $(this).closest('tr').find('.memid').val(),
        type: $(this).closest('tr').find('.type').val(),
        status: $(this).closest('tr').find('.status').val()
      };
      console.log(dataString);
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/memberships.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $('.overlay').fadeIn();
        },
        success: function(json){
          $('.message').html(json.status);
          setTimeout(function(){
            $('.overlay').fadeOut();
            $('.message').fadeIn();
            $('#mbslist').html(json.table).fadeIn();
          }, 2000);
        }
      });
      return false;
    });
});

进程/memberships.php

<?php
include('../../config/db.php'); include('../../functions.php');

$memid  = (!empty($_POST['id']))?$_POST['id']:null;
$type   = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;

$color   = (!empty($_POST['color']))?$_POST['color']:null;
$name    = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount  = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay  = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price   = (!empty($_POST['price']))?$_POST['price']:null;

if($_POST){
  if($type == 'memstatus'){
    $update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
    $update-> bindValue(':status', $status);
    $update-> bindValue(':id', $memid);
    $update-> execute();

    if($update){
      $pro = $pdo->prepare("SELECT * FROM memberships");
      $pro-> execute();

      $table = "<table class='table table-hover table-striped' id='mbslist'>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Daily Capping</th>
                    <th>Commission</th>
                    <th>Payout</th>
                    <th>Payout %</th>
                    <th>Cost</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>";

        $i = 1;
        while($p = $pro->fetch()){ extract($p);
          if($mem_status == 'enabled'){
            $statusColor = "text-success";
            $btn = "btn-danger";
            $status = "disabled";
            $btnVal = "Disable";
          }else{
            $statusColor = "text-danger";
            $btn = "btn-success";
            $status = "enabled";
            $btnVal = "Enable";
          }
          if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
        $table .= "<tr>
                    <td>".$i."</td>
                    <td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
                    <td>&#8377;".$mem_daily_capping."</td>
                    <td>&#8377;".$mem_earn_amount."</td>
                    <td>&#8377;".$mem_min_payout."</td>
                    <td>".$mem_payout_percent."%</td>
                    <td>".$mp."</td>
                    <td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
                    <td>
                      <form method='post' action=''>
                        <input type='hidden' value=".$mem_id." class='memid'>
                        <input type='hidden' value=".$status." class='status'>
                        <input type='hidden' value='memstatus' class='type'>
                        <input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
                        <a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
                      </form>
                    </td>
                  </tr>";
        $i++;
      }

      $table .= "</table>";
     echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
   }else{
     echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
   }
  }
}

【问题讨论】:

标签: javascript php jquery json ajax


【解决方案1】:

使用以下代码修改您的 processes/memberships.php:

$memid  = (!empty($_POST['id']))?$_POST['id']:null;
$type   = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;

$color   = (!empty($_POST['color']))?$_POST['color']:null;
$name    = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount  = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay  = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price   = (!empty($_POST['price']))?$_POST['price']:null;

if($_POST){
  if($type == 'memstatus'){
    $update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
    $update-> bindValue(':status', $status);
    $update-> bindValue(':id', $memid);
    $update-> execute();

    if($update){
      $pro = $pdo->prepare("SELECT * FROM memberships");
      $pro-> execute();

      $table = "<table class='table table-hover table-striped' id='mbslist'>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Daily Capping</th>
                    <th>Commission</th>
                    <th>Payout</th>
                    <th>Payout %</th>
                    <th>Cost</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>";

        $i = 1;
        while($p = $pro->fetch()){ extract($p);
          if($mem_status == 'enabled'){
            $statusColor = "text-success";
            $btn = "btn-danger";
            $status = "disabled";
            $btnVal = "Disable";
          }else{
            $statusColor = "text-danger";
            $btn = "btn-success";
            $status = "enabled";
            $btnVal = "Enable";
          }
          if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
        $table .= "<tr>
                    <td>".$i."</td>
                    <td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
                    <td>&#8377;".$mem_daily_capping."</td>
                    <td>&#8377;".$mem_earn_amount."</td>
                    <td>&#8377;".$mem_min_payout."</td>
                    <td>".$mem_payout_percent."%</td>
                    <td>".$mp."</td>
                    <td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
                    <td>
                      <form method='post' action=''>
                        <input type='hidden' value=".$mem_id." class='memid'>
                        <input type='hidden' value=".$status." class='status'>
                        <input type='hidden' value='memstatus' class='type'>
                        <input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
                        <a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
                      </form>
                    </td>
                  </tr>";
        $i++;
      }

      $table .= "</table>";
     echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
   }else{
     echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
   }
  }
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
    $(".mbslist").click(function() {
      var dataString = {
        id: $(this).closest('tr').find('.memid').val(),
        type: $(this).closest('tr').find('.type').val(),
        status: $(this).closest('tr').find('.status').val()
      };
      console.log(dataString);
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/memberships.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $('.overlay').fadeIn();
        },
        success: function(json){
          $('.message').html(json.status);
          setTimeout(function(){
            $('.overlay').fadeOut();
            $('.message').fadeIn();
            $('#mbslist').html(json.table).fadeIn();
          }, 2000);
        }
      });
      return false;
    });
});
</script>

希望这对你有帮助。

【讨论】:

  • 并且这个 AJAX 代码将加载到 while 循环中的每个表行中?你真的认为这是个好主意吗?另外,这不起作用。
  • 等等.. 我修改了它并将它放在$table 变量中作为变量的扩展。现在它的工作。但这真的是个好主意吗?
  • 我已经更正了您的回答,因为它对我有帮助,并接受它作为目前解决我的问题的方式。但是,我不能赞成它,因为我不确定这是否是解决问题的最佳方法。不管怎么说,还是要谢谢你。至少目前它运作良好。你回答的方式实际上并没有解决问题,但给了我一个解决问题的想法。
【解决方案2】:

您的提交按钮将在您单击它时尝试正常提交表单。所以只需使用下面的“event.preventDefault()”,这样你的按钮就不会触发正常的表单提交,现在也不会加载页面。

$(".mbslist").click(function(event) {
  event.preventDefault();
}

【讨论】:

  • 不..那没用..我已经试过了..它仍然用新加载的表格刷新页面..
  • 你试过从form标签中取出method="post"吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多