访问函数中创建的javascript对象

时间:2014-02-06 15:42:36

标签: javascript ajax variables object

我正在使用结合php对象的javascript对象开始我的第一步。到目前为止一切正常,但我很难访问在此函数之外的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未定义。如何在currentSettings功能之外访问onSuccess

谢谢!

2 个答案:

答案 0 :(得分:2)

Ajax是异步的,因此最后一个console.log将在调用成功函数之前执行。

答案 1 :(得分:1)

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);
}