首页 > 解决方案 > 在 Ajax 请求中访问 JavaScript 变量,以便在另一个函数中使用?

问题描述

我正在使用 Ajax 填充员工的全局列表,可以选择在表单中使用这些员工。现在一切正常,但我唯一想做的就是访问 Ajax 请求中的一个变量,以便在另一个函数中使用。该变量是一个 JavaScript 对象,我想用它来使用员工数据预先填充表单的字段。我将缩短 HTML 以获得更好的可读性,并显示我唯一关心的字段。

Ajax 函数中的<input>标记调用该addEmployee函数以在后端添加员工。

  $("#email, #phone").change(function () {
  let phone =  $('#phone').val();
  let email =  $('#email').val();


  $.ajax({
    url: '/employee/add/',
    data: {
        'phone': phone,
        'email': email,
    },
    dataType: 'json',
    success: function (data) {
      if (data) {
            $('#employee_list').html("");
            let res = data.emp_list;
            if (res.length > 0) {
                for (let i = 0; i < res.length; i++) {
                    let html_string = '';
                    let data = res[i];
                    //I would like to access this ^^ data variable in the addEmployee function

                    html_string += '<input onchange="addEmployee(this)" type="checkbox"  id="' + data.id + '" name="remember_me" value="' + data.id + '"' + (data.selected ? 'checked' : '') + '>'

                   // There are a bunch of other html strings that just populate the list with the 
                   //data variable, and access that object properties, such as data.first_name, data.last_name etc.

                 

                    html = $.parseHTML(html_string);
                    $('#employee_list').append(html);
                }

            } else {
                $("#emp-list-head").hide();

            }
      }
    }

  });

});


function addEmployee(checkbox) {
    if ($(checkbox).is(':checked')) {
        $("<input>").attr({
            name: "hidden_id",
            id: "hidden_id",
            type: "hidden",
            value: checkbox.value
        }).appendTo($('#add_employee_form'));
        // Down here I would like to access the data variable from the ajax function to prepopulate my form
        $('#emp_first_name').val(where I would like to access data.first_name);
    }
} 

这是可能的,还是需要完成额外的功能才能data从 ajax 函数访问变量以在函数中使用addEmployee

我什至尝试将data对象本身添加到自定义 htmldata-value属性中,如下所示,

html_string += '<input onchange="addEmployee(this)" type="checkbox"  id="' + data.id + '" name="remember_me" data-value="' + data + '"' + value="' + data.id + '"' + (data.selected ? 'checked' : '') + '>'

这像这样返回了data-value[object Object],

<input onchange="addEmployee(this)" type="checkbox" id=3 name="remember_me" data-value="[object Object]" value=3>

任何帮助是极大的赞赏!

标签: javascriptjqueryajax

解决方案


推荐阅读