【问题标题】:How to return result from function that has an $.ajax call如何从具有 $.ajax 调用的函数返回结果
【发布时间】:2013-02-14 16:33:37
【问题描述】:

我会马上说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(或任何值),以便我可以在上面的代码中使用它?

【问题讨论】:

  • 答案的重点是你不应该从这个函数返回结果。 AJAX 是异步,所以函数在调用完成之前返回。无论你想做什么,都应该在回调中完成。
  • 知道了,巴尔玛。谢谢 - 功能现在可以根据需要工作。

标签: function jquery return-value


【解决方案1】:

将 ajax 调用异步选项设置为 false。然后你会得到结果。 见链接https://stackoverflow.com/a/1531710/399414

$.ajax({
        type: 'POST',
        async: false,
        url: '../scripts/branchAdmin.php',
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2021-09-11
    • 2020-03-15
    • 2021-06-03
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多