0

当我调用这个函数时,我收到了我想要的正确数组,但是一旦我尝试返回它,控制台就会告诉我“选项”是未定义的。有任何想法吗?

function getOptionsJSON(Ordernumber) {

    $.getJSON(window.location.pathname+'/ajaxRequest?ordernumber='+Ordernumber+'&'+Math.round(new Date().getTime()), function(data) {
        if(data['articleID']) {
            options = data['values_label_array'];   
            console.log(options)    // returns {"1":"Option 1","2":"Option 2"}
            }       
    });
    console.log(options) // returns Undefined
    return options;     
}


function selectOptions(){
    var options = getOptionsJSON($(row).find('.ordernumber').val());
    console.log(options)     //  returns Undefined  
}

这是在 AjaxREquestAction 中调用的 PHP 函数:

$returnData["values_label_array"] = json_encode($this->getOptionsAction($ordernumber)); 
4

3 回答 3

1

您正在调用其范围之外的选项。你在一个函数中声明了它,所以它的作用域是那个函数。您需要在全局范围内声明它。

于 2014-02-15T15:43:10.117 回答
0

问题是 getJSON 是异步的。

console.log(operations) 在 JSON 请求实际完成之前执行。您可以在 console.log 中看到这一点,其中未定义的行将出现在选项上方。

在 function(data) 内部,您需要调用处理器而不是让 getOptionsJSON 返回选项。

你可以简单地做到这一点

$.getJSON(window.location.pathname+'/ajaxRequest?ordernumber='+Ordernumber+'&'+Math.round(new Date().getTime()), function(data) {
    if(data['articleID']) {
        options = data['values_label_array'];   
        console.log(options)    // returns {"1":"Option 1","2":"Option 2"}
        processJSON(options );
     }       
});

function selectOptions(){
    getOptionsJSON($(row).find('.ordernumber').val());
}

function processJSON(data) {
   //do something with the JSON;
}
于 2014-02-15T15:46:06.360 回答
0

您必须在函数内声明一个变量。在函数外部无法访问内部函数变量

function getOptionsJSON(Ordernumber) {

    //declare variable here and then assign the values
    var options;

    $.getJSON(window.location.pathname+'/ajaxRequest?ordernumber='+Ordernumber+'&'+Math.round(new Date().getTime()), function(data) {
        if(data['articleID']) {
            options = data['values_label_array'];   
            console.log(options)    // returns {"1":"Option 1","2":"Option 2"}
            }       
    });
    console.log(options) // returns Undefined
    return options;     
}


function selectOptions(){
    var options = getOptionsJSON($(row).find('.ordernumber').val());
    console.log(options)     //  returns Undefined  
}
于 2014-02-15T15:53:11.630 回答