javascript - 在 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>
任何帮助是极大的赞赏!
解决方案
推荐阅读
- php - PHP 警告:fsockopen(): 无法连接到 example.com:8010(连接被拒绝)CentOS SELinux
- amp-html - 如何修复在 AMP 中提交时的联系表单错误?
- unix - 使用 last 获取用户的最后 8 次登录
- google-apps-script - 如何让用户使用 Google 登录以访问已部署的 GAS Web 应用程序?
- r - 我可以从包中的函数更新 R 包中的数据吗?
- html - 如何使用 flexbox 在每个断点处居中 div?
- error-handling - 系统编程 qemu:未知键码 `(unnamed)'
- download - Mikrotik 对热点配置的带宽限制
- javascript - TypeError:无法读取未定义的属性“随机”-crypto-js
- python - 为什么简单的 .apply(...) 会产生 SettingWithCopyWarning?