我会马上说this question似乎解决了同样的情况,但对于我的生活,我没有看到解决方案/答案是什么。也许有人只需要为我更清楚地“拼出来”!
我有以下功能:
function CheckIfUrlExists(checkUrl) {
var exists = '';
$.ajax({
type: 'POST',
url: '../scripts/branchAdmin.php',
data: {checkUrl: checkUrl},
cache: false,
success: function(response) {
console.log('response: ' + response);
if (response === 'true') {
exists = 'true';
} else if (response === 'false') {
exists = 'false';
}
},
error: function(response) {
// return false and display error(s) from server
exists = 'false';
}
});
console.log('exists: ' + exists); // always displays empty string, regardless of what the php script returns
return exists;
}
我用它来称呼它:
var exists = CheckIfUrlExists($tr.find('input.editUrl').val());
if (exists === 'false') {
//if (!CheckIfUrlExists($tr.find('input.editUrl').val())) {
// New URL entered, verify user want to save it
$('#confirmAddNewUrlDialog').data('row', $tr).dialog('open');
... // code to handle result
}
如何让“CheckIfUrlExist()函数返回true或false(或任何值),以便我可以在上面的代码中使用它?
答案 0 :(得分:0)
将ajax调用async选项设为false。然后你会得到结果。 请参阅链接https://stackoverflow.com/a/1531710/399414
$.ajax({
type: 'POST',
async: false,
url: '../scripts/branchAdmin.php',
...