首页 > 解决方案 > 跨多个 Ajax POST 调用在成功函数中存储和更新全局值

问题描述

我有两个 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;

    }
  });
}

标签: javascripthtmljqueryajax

解决方案


试试这个

$.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')
    }
});


推荐阅读