简体   繁体   English

AJAX调用后在jQuery中更新变量

[英]update variable in jQuery after AJAX call

My AJAX function is below working successfully until someone resubmits the AJAX call without a page refresh . 在有人resubmits the AJAX call without a page refresh之前,我的AJAX功能resubmits the AJAX call without a page refresh正常工作。 In this case, the AJAX call uses the old value of var amount rather than an updated one. 在这种情况下,AJAX调用使用var amount的旧值而不是更新后的值。 Therefore, I need to update var amount at the end of my success function but am failing to do so. 因此,我需要在成功函数的末尾更新var数量,但未能这样做。

$(document).on('click', '#updateBidButton', function (e) {
  e.preventDefault();

  var amount = ('#curr_bid').val()
  var expire_date = "<?php echo $this->item['expire_date']?>";

  $.ajax({
    type: 'post',
    url: "?module=items&controller=index&action=submit",
    dataType: "text",
    data: 'amount=' + amount + '&expire_date=' + expire_date,
    beforeSend: function () {
      $('.auction_box').animate({
        'backgroundColor': '#ffdead'
      }, 400);
    },
    success: function (result) {
      if (result == 'ok') {
        $('.auction_box').animate({
          'backgroundColor': '#A3D1A3'
        }, 500);
        amount = $('#curr_bid').val();
        setTimeout(function () {
          $('.auction_box').css('background-color', '#FFF');
        } , 5000);
      }
    }       
  });
});

in your code amount variable not updated, use 在您的代码量变量未更新中,使用

   var newValue = ''; // for example get new value from ajax response 
   $('#curr_bid').val(newValue)

for updating 用于更新

Here you go with a solution 在这里你有一个解决方案

$(document).on('click', '#updateBidButton', function (e) {
  e.preventDefault();

  var amount = $('#curr_bid').val()
  var expire_date = "<?php echo $this->item['expire_date']?>";

  $.ajax({
    type: 'post',
    url: "?module=items&controller=index&action=submit",
    dataType: "text",
    data: 'amount=' + amount + '&expire_date=' + expire_date,
    beforeSend: function () {
      $('.auction_box').animate({
        'backgroundColor': '#ffdead'
      }, 400);
    },
    success: function (result) {
      if (result == 'ok') {
        $('.auction_box').animate({
          'backgroundColor': '#A3D1A3'
        }, 500);
        setTimeout(function () {
          $('.auction_box').css('background-color', '#FFF');
        } , 5000);
      }
    }       
  });
});

Missing $ in 3rd line. 第三行缺少$ No need to reassign the value to amount variable in success method. 在成功方法中,无需将值重新分配给amount变量。

As you click amount variable will get the latest value from input#curr_bid . 单击时, amount variable将从input#curr_bid获取最新值。

Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM