获取函数外部变量的值

时间:2019-03-20 08:46:57

标签: javascript jquery

我正在使用可排序的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')
  },

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

不公开任何全局变量。

$(function() {
   var li_id, end_pos;
   $('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');
  li_id = $(li).attr('data-id'), // send this value in ajax call
  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')
}
 });
});

答案 2 :(得分:0)

您可以在函数外部声明它们,然后在函数内部分配它们:

var li_id, end_pos;

$(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');
      li_id = $(li).attr('data-id'), // send this value in ajax call
      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')
    }
  });
});