【问题标题】:Access javascript object created in a function访问在函数中创建的 javascript 对象
【发布时间】:2014-02-06 15:42:35
【问题描述】:

我正在使用 javascript 对象与 php 对象相结合来迈出第一步。到目前为止一切正常,但我很难在此函数之外访问在 ajax 成功响应中创建的 javascript 对象。

这是我的 JS 代码:

function settings(mannstage, stundenlohn, tags) {
    this.mannstage = mannstage;
    this.stundenlohn = stundenlohn;
    this.tags = tags;
}
var currentSettings;
SendAjaxJsonRequest("getSettings");

function SendAjaxJsonRequest(method, jsonObject) {
    jsonObject = (typeof jsonObject === "undefined") ? "none" : jsonObject;
    $.ajax({
        type: "POST",
        url: "app/class/controller/ajax.php",
        data: {
            method: method,
            jsonObject: jsonObject
        },
        success: onSuccess
    })
};

function onSuccess(content) {

    var response = $.parseJSON(content);
    currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
    console.log(currentSettings); //Returns the object
}
console.log(currentSettings); //This is undefined

最后一个 console.log 未定义。如何在onSuccess 函数之外使currentSettings 可访问?

谢谢!

【问题讨论】:

    标签: javascript ajax variables object


    【解决方案1】:

    Ajax是异步的,所以最后一个console.log会在调用success函数之前执行。

    【讨论】:

      【解决方案2】:

      currentSettings 可在onSuccess 函数之外访问,但您的最后一次console.log 调用在onSuccess 定义之后立即运行,即在它被调用之前,所以此时currentSettings的值仍然是undefined

      也许像这样编辑您的代码会证明这一点:

      function onSuccess(content) {
      
          var response = $.parseJSON(content);
          currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
          console.log(currentSettings); //Returns the object
          afterSuccess(); // Also returns the object
      }
      
      function afterSuccess() {
          console.log(currentSettings);
      }
      

      【讨论】:

      • 我没有考虑ajax的异步性。非常感谢!
      • @Sebsemillia:不客气。 “A”代表异步! (但“X”又是“XML”,所以首字母缩写词可能不是特别相关。)
      • 呵呵,我知道了!但现在我会记得.. ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多