我对这个 JavaScript 函数有疑问。我想做的是,使用 ajax 调用查找特定的“ Material 描述”。当我尝试 console.log ajax 函数时,数据会显示出来。但是当我设置为数组时,它不会设置数组值并跳过。使用“async: false”给我这个警告:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.
没有异步会给我不确定的结果。
$('#iBarcode').keypress(function (keyPressed) {
if (keyPressed.which == 13) {
var barcode = $('#iBarcode').val()
var splitted = new Array()
var arrayCnt = -1;
for (var i = 0; i < barcode.length; i++) {
var flagStart;
if (barcode.charAt(i) == ')') {
flagStart = true
i += 1
arrayCnt += 1
splitted[arrayCnt] = ''
}
if (barcode.charAt(i) == ('(')) {
flagStart = false
}
if (flagStart == true) {
splitted[arrayCnt] = splitted[arrayCnt] + barcode.charAt(i)
}
}
console.log(setMatDesc(splitted[0])) //value showed here
splitted[arrayCnt + 1] = setMatDesc(splitted[0]) //value not showed here and skipped?
splitted[arrayCnt + 1] = currentDate
$('#iBarcode').val('').focus
console.log(splitted)
}
})
function setMatDesc(MatID) {
var result
$.ajax({
url: '@Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
result=data
},
error: function (xhr) {
alert('error');
}
})
return result
}
非常感谢您的帮助,谢谢。
最佳答案
您需要提供一个回调函数,该函数将在 ajax 调用完成后执行,如下所示:
function setMatDesc(MatID, calback) {
var result
$.ajax({
url: '@Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
callback(data); // note this
},
error: function (xhr) {
alert('error');
}
});
}
并在调用结束时执行以下操作:
setMatDesc(splitted[0],function(result) {
splitted = result;
splitted[arrayCnt + 1];
splitted[arrayCnt + 1] = currentDate;
});
代码可能无法工作,因为我没有测试过,但这是从执行 ajax 调用的函数返回数据的方法,因为 ajax 调用是异步执行的,并且函数在 ajax 调用从服务器完成之前执行主体。
关于javascript - ajax 未在声明的变量上设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511992/