0

我正在尝试创建一个函数,这是通过 PHP 获取格式化字符串形式的 JSON 数据。但是我无法通过此函数获取格式化字符串。

下面的 JavaScript 代码:

function getJSON2Str(opt){
    var url='t4action.php',returnStr='',i=1;
    var textInfo ="";
    $.getJSON( url , 'opt='+opt, function (data){
        $.each(data,function(){
            returnStr+= this.opid + ':' + this.opcont;
            if( i < data.length ) returnStr += ';';
            i++;
        })
        //alert(returnStr); //<--here is works to show string 'returnStr'.
    });
    //alert(returnStr);  //<-- here is NOT works to show string 'returnStr'.
    return returnStr;   //<-- finally I want to return 'returnStr' for other use.
}

alert(getJSON2Str('getEduOption'));  //<-- here just show a empty string.

t4action.php 代码很简单,只是从数据库中返回一些数据。例如:

<?php
$returnArr[0]['opid']=2;
$returnArr[0]['opcont']='high school';
$returnArr[1]['opid']=5;
$returnArr[1]['opcont']='university';
$returnArr[2]['opid']=8;
$returnArr[2]['opcont']='elementary school';
$returnArr[3]['opid']=9;
$returnArr[3]['opcont']='research institute';

echo json_encode($returnArr);
?>

我应该怎么做才能让功能正常工作?谢谢!

我在 jqGrid 搜索属性中使用它,如下所示:

.....
search:true, stype:'select', searchrules:{required:true}, searchoptions:{value:getJSON2Str('getEduOption'), sopt:['eq']},
....

我知道我可以将dataUrl属性与buildSelect一起使用来构建选择元素。但就我而言,选项显示在搜索和编辑表单中,但不在列表中。所以我尝试这种方式让它工作。如果我使用下面的那个功能是有效的。

function getJSON2Str(opt){
    return '0:--;2:high school;5:university;8:elementary school;9:research institute';
}
4

1 回答 1

0

$.getJSON是异步的,因此在返回return returnStr;空字符串之后立即执行。您需要将代码更改为:

function getJSON2Str(opt,callback){
    var url='t4action.php',returnStr='',i=1;
    var textInfo ="";
    $.getJSON( url , 'opt='+opt, function (data){
        $.each(data,function(){
            returnStr+= this.opid + ':' + this.opcont;
            if( i < data.length ) returnStr += ';';
            i++;
        })
        if (typeof callback === "function"){
            callback(returnStr);
        }
    });
}

用它:

getJSON2Str('getEduOption', function(returnStr){
   alert(returnStr);
});

在你的情况下,像这样使用它:

getJSON2Str('getEduOption', function(returnStr){
     var searchParam = {search:true, stype:'select', searchrules:{required:true}, searchoptions:{value:returnStr, sopt:['eq']};
     //your search function
});
于 2013-05-26T11:29:12.753 回答