我有一个页面,我可以在其中输入卡片名称,卡片的详细信息通过 AJAX 呈现。我在这个例子中删除了很多与问题无关的代码,我测试了这个简化的代码,它重现了同样的错误。
神奇的是它在第一次运行 testSelectedCardDetails
函数时运行良好。它可以很好地调用 setNameCardIsFromField
并执行其预期的操作。第二次通过它时控制台显示:
Uncaught TypeError: setNameCardIsFromField is not a function
这是怎么回事?老实说,我不太了解 jQuery 是如何工作的,无法解决这个问题,所以我求助于 stackoverflow 世界,希望从这种疯狂中解脱出来。 ;)
function testSelectedCardDetails(cardName) {
var cardTestInfoArray = [];
$.ajax({
url: 'includes/getCardAndSetDataViaAJAX.php',
type: 'POST',
cache: false,
async: false, // if set to true then the data doesn't get here fast enough to run commands in 'success'
dataType: 'json',
data: { callThis: "testSelectedCardDetails", thisCardName: cardName},
error: function(data){
console.log("AJAX failed to get card info.");
},
success: function(data) {
$.map(data, function (value) { cardTestInfoArray = value; });
cardPresentInfo['printings'] = cardTestInfoArray['printings'];
//automatically set setNameCardIsFrom field
setNameCardIsFromField(cardPresentInfo['printings']);
}
});
}
这是被调用的函数:
function setNameCardIsFromField(setCode) {
$.ajax({
url: 'includes/getCardAndSetDataViaAJAX.php',
type: 'POST',
cache: false,
async: false, // if set to true then the data doesn't get here fast enough to run commands in 'success'
dataType: 'text',
data: { callThis: "setNameCardIsFromField", thisSetCode: setCode},
error: function(data){
console.log("AJAX failed to get card info.");
},
success: function(setName) {
//console.log(setName);
setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');
setNameCardIsFromField.value = setName;
}
});
}
最佳答案
你覆盖函数:
setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');
假设它是全局的(这通常是不好的)。
不相关,但是关于使用 async: false
,最好正确地使用它而不是绕过它,例如回调、promise 等等。
关于javascript - jQuery ajax 成功响应中的调用函数工作一次但不是两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001724/