首页 > 解决方案 > 获取函数外变量的值

问题描述

我正在使用可排序的 jquery,我正在获取 li 的索引值及其更改属性。我想通过ajax发送索引值和属性值。这是我的代码:

$(function() {
  $('ul').sortable({
    start: function(event, ui) {
      var start_pos = ui.item.index();
      ui.item.data('start_pos', start_pos);
    },
    update: function(event, ui) {
      var start_pos = ui.item.data('start_pos');
      var li_id = $(li).attr('data-id'), // send this value in ajax call
        var end_pos = ui.item.index(); //send this value in ajax call
    }
  });
});

我想发送这些值是这样的:

$.ajax({
  type: "GET",
  dataType: "json",
  url: `${SiteConfig.staticContentBaseUrl}/sortabletable`,
  data: {
    id: li_id,
    position: end_pos,
    _token: $('meta[name=csrf-token]').attr('content')
  },

如何访问函数外部的变量值?

标签: javascriptjquery

解决方案


将这两个功能分开,因为它们实际上是两个不同的工作。

$(function() {
  $('ul').sortable({
    start: function(event, ui) {
      var start_pos = ui.item.index();
      ui.item.data('start_pos', start_pos);
    },
    update: function(event, ui) {
      var start_pos = ui.item.data('start_pos');
      var li_id = $(li).attr('data-id'), // send this value in ajax call
        var end_pos = ui.item.index(); //send this value in ajax call
      do_ajax(li_id, end_pos); //do ajax here
    }
  });
});

function do_ajax(li_id, end_pos) {
  $.ajax({
    type: "GET",
    dataType: "json",
    async: true, //I added this for better user experience if nothing else depends on it.
    url: `${SiteConfig.staticContentBaseUrl}/sortabletable`,
    data: {
      id: li_id,
      position: end_pos,
      _token: $('meta[name=csrf-token]').attr('content')
    }
  });
}

推荐阅读