如何将变量从一个函数传递到另一个函数或访问全局变量?

时间:2014-01-28 09:15:23

标签: javascript ajax json

我在我的应用程序的一小部分中使用ajax将表单变量发布到php脚本,该脚本向我的api发出查询。

这是表格

<input name="answer_id" id="answer_id<?= $i;?>" type="radio" style="width: 21px" value="<?= $ans_id; ?>"> <!-- I have a for loop here that provides 3 different answers for the radio button -->
<input name="question_id" id="question_id" type="hidden" style="width: 21px" value="<?= $question_id; ?>">
<input name="all_answers" id="all_answers" type="hidden" style="width: 21px" value='<?= serialize($answers); ?>'>
<input name="Submit" onclick="post_question()" type="submit" value="Submit" class="btn btn-success">
<input type="hidden" id="campaign_id" value="<?= $campaign; ?>">

post_question()函数

var responseData = [];
function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data);
    var tempVar = responseData['response'];//The problem begins here. responseData['response'] appears to be an empty string
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
}

load_post()函数

function load_post(url, params){
    new imageLoader(cImageSrc, 'startAnimation()');
    var xhr,
        response = [];
    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0",
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]
        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
                break;
            }
            catch(e){}
        } // end for
    }
    xhr.onreadystatechange = ensureReadiness;
    function ensureReadiness() {
        if (xhr.readyState !== 4) {
            return;
        }
        responseData['response'] = xhr.responseText;
        responseData['code'] = xhr.status;
    }

    xhr.open('POST', url, true);
    xhr.send(params);
    responseData['response'] = xhr.responseText;
    responseData['code'] = xhr.status;
    return responseData;
}

变量responseData是一个全局变量。这是一个数组。 responseData['response']是一个包含对象的json数组。

[{"id":"10082","question_id":"26","answer_id":"46","profile_id":"42121","correct":"1","attempts":"8"}]

,这是从post_question.php页面返回的内容。我无法做的是访问该JSON对象,我已经尝试将其存储在全局变量中,并且我已经尝试将其传递给另一个函数但没有成功。由于某种原因,全局变量表示它是一个空字符串。但是,使用firebug检查responseData变量,这就是我得到的:

The Console

This didn't quite solve my problemneither did this还有一些我去过的其他资源并没有帮助解决我的问题。 我想要的是传递在load_post()中保存的responseData变量或者从post_question()函数访问该变量,它毕竟是一个全局变量。任何帮助,将不胜感激。 附:我是javascript的新手。

1 个答案:

答案 0 :(得分:0)

这行代码

load_post("controllers/post_question.php", data);

是异步的,因此以下行将访问responseData中的空数组。

要处理AJAX调用的异步性质,您必须传递一个将在AJAX任务结束时调用的回调,如:

function load_post(url, params, callback){
    new imageLoader(cImageSrc, 'startAnimation()');
    var xhr,
        response = [];
    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0",
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]
        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
                break;
            }
            catch(e){}
        } // end for
    }
    xhr.onreadystatechange = ensureReadiness;
    function ensureReadiness() {
        if (xhr.readyState !== 4) {
            return;
        }
        responseData['response'] = xhr.responseText;
        responseData['code'] = xhr.status;
        callback(responseData);
    }

    xhr.open('POST', url, true);
    xhr.send(params);

  }

  function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data, processNewData);
  }

  function processNewData(newData){
    var tempVar = newData['response']; // or you can use responseData at this point as well
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
  }

在上面的实现中,我传递responseData作为回调的参数,但是因为它是一个全局变量,你也可以在没有参数的情况下调用回调并在需要时访问它。