【问题标题】:Javascript (jQuery) - Weird undefined variableJavascript (jQuery) - 奇怪的未定义变量
【发布时间】:2021-11-19 11:30:34
【问题描述】:

这是我的 jQuery 函数

function addEntryDatabase(data){
    var entryId;
    $.ajax({
        url: "model/script_ajout.php",  
        async: false,
        type: "POST",
        dataType: 'html',
        data: data
        success: function()
        {

        },
        error: function(){
            console.log('An error occurred while adding adata to the database.');
        }
    });
    return entryId;
}

这是我的代码

/**
 * Creating user in the database
 */
var user_id = addEntryDatabase(data);
console.log(user_id);

这是我的网络浏览器的控制台(一切都很好,我得到了我的 entryId 值)

但我的 user_id 的 console.log 给我“未定义”。 我无法解释为什么。

有人知道为什么吗?

【问题讨论】:

  • 你声明 entryId 没有值 (var entryId;) 然后你返回它 (return entryId;)。您绝不会为其分配值。 默认值undefined

标签: jquery variables undefined


【解决方案1】:

成功后,您需要将您的entryId 更改为您收到的回复,其中您将拥有您想要登录的ID。

function addEntryDatabase(data){
    var entryId;
    $.ajax({
        url: "model/script_ajout.php",  
        async: false,
        type: "POST",
        dataType: 'html',
        data: data
        success: function()
        {
          entryId= response.data.id ///change your entryId;
        },
        error: function(){
            console.log('An error occurred while adding adata to the database.');
        }
    });
    return entryId;
}```

【讨论】:

  • 这么简单..谢谢!
  • 欢迎。请接受解决方案:)
  • 如果您尝试在 AJAX 请求完成之前访问结果(或者如果它出错),则该值仍然是未定义的。
  • 是的,只有出现错误才会给出 undefined。
猜你喜欢
  • 2012-07-11
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2010-12-20
  • 2012-05-16
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
相关资源
最近更新 更多