【问题标题】:Storing and updating a global value in the success function across multiple Ajax POST calls跨多个 Ajax POST 调用在成功函数中存储和更新全局值
【发布时间】:2021-01-28 09:30:21
【问题描述】:

我有两个 HTML 元素:1)。 div 元素是一个多选(它是一个预定义的小部件,会自动创建多选元素)和 2)。触发 onclick 事件的按钮。 在 JS 方面,全局变量“prev_selection”暂时设置为空数组。 prev_selection 的想法是在用户单击按钮之前记住多选 div 元素中的值数组。我想记住单击前后的值,以查看添加/删除了哪些选择。

单击按钮时,会调用“sendData()”。它从 div 元素中获取选定的数据。然后,它使用 prev_selection 执行一些操作,以了解新选择的值是什么(一开始,div 中的所有内容都是新选择的)。

我想在用户点击之间找出所选值中的添加/删除。为此,我使用单击后从 div 元素中获取的“selected_data”更新 prev_selection。

但这并没有按预期工作。异步 Ajax 调用发生了一些事情,我无法为此找到更好的解决方案。每次单击发生时,您都希望“prev_selection”记住单击之前的值,但是当我使用 console.log() 打印它时(如代码所示),它甚至在达到成功功能之前就已经更新为最新的选择(应该更新的地方)。

提前致谢!如果需要进一步解释,请告诉我。

<!-- multiple select/deselect div -->
<div id="someSelectionID"></div>
<button id="updateButtonID" onclick="sendData()">Click to send</button>
// at first, no data is selected
var prev_selection = [];

function sendData() {
  // get the selected data from the div element "someSelectionID"
  let selected_data = $('#someSelectionID').val();

  // perform some operations on the selected data
  // this operation involves the use of prev_selection

  // printing prev_selection already has value of updated click
  console.log(prev_selection );

  $.ajax({
    type: "POST",
    url: "<some url>",
    dataType: 'json',
    contentType: 'application/json;charset=UTF-8',
    data: JSON.stringify( < some data > ),
    success: function(result) {
      console.log(result);

      /* once the request is successfully done update the 
      previous selection to what the current selected data is */
      prev_selection = selected_data;

    }
  });
}

【问题讨论】:

    标签: javascript html jquery ajax


    【解决方案1】:

    试试这个

    $.ajax({
        type: "POST",
        url: "<some url>",
        dataType: 'json',
        contentType: 'application/json;charset=UTF-8',
        data: JSON.stringify( < some data > ),
        }
      }).then(function(response){
        if (response.status === 200){
          console.log('succeed');
        } else {
          console.log('failed')
        }
    });

    【讨论】:

      【解决方案2】:

      所以它通过改变这一行来工作

      prev_selection = selected_data;
      

      到:

      prev_selection = Array.from(selected_data);
      

      因为 prev_selection 变量在我没有更新的情况下不断变化,这让我相信它是对值的某种引用,而不是对值本身的引用。所以仅仅使用 Array.from 来做一个浅拷贝实际上是有效的。

      【讨论】:

        猜你喜欢
        • 2012-08-26
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多