1

出于某种原因,在.done()成功的 AJAX 调用后该函数未触发。这是 Javascript 文件:

//Create groups
$("#compareschedulesgroups_div").on('click', '.compareschedules_groups', function() { //When <li> is clicked
    //Get friendids and friend names
    print_loadingicon("studentnames_taglist_loadingicon");
    $.ajax({
        type: "POST", //POST data
        url: "../secure/process_getgroupdata.php", //Secure schedule search PHP file
        data: { groupid: $(this).find(".compareschedules_groups_groupnum").val() }, //Send tags and group name
        dataType: "JSON" //Set datatype as JSON to send back params to AJAX function
    })
    .done(function(param) { //Param- variable returned by PHP file
        end_loadingicon("studentnames_taglist_loadingicon");
        //Do something
    }); 
});

Safari 的 Web 开发选项卡说我的外部 PHP 文件返回了这个,这是正确的数据:

{"student_id":68,"student_name":"Jon Smith"}{"student_id":35,"student_name":"Jon Doe"}{"student_id":65,"student_name":"Jim Tim"}{"student_id":60,"student_name":"Jonny Smith"}

PHP 文件如下所示。基本上,它获取一个 json_encoded 值,回显一个 Content-Type 标头,然后回显 json_encoded 值。

    for ($i = 0; $i<count($somearray); $i++) {
        $jsonstring.=json_encode($somearray[$i]->getjsondata());
    }

    header("Content-Type: application/json", true);
    echo $jsonstring;

编辑:我有一个对象数组-这是进行 json_encoding 的方法吗?

getjsondata 函数是这样的,来自另一个 Stack Overflow 问题:

    public function getjsondata() {
        $var = get_object_vars($this);
        foreach($var as &$value){
           if(is_object($value) && method_exists($value,'getjsondata')){
              $value = $value->getjsondata();
           }
        }
        return $var;
    }
4

1 回答 1

2

您正在循环json_encode()调用,输出单个对象。当它们连接在一起时,这是无效的 JSON。解决方案是将每个对象附加到一个数组,然后对最终数组进行编码。将 PHP 更改为:

$arr = array();

for ($i = 0; $i<count($somearray); $i++) {
    $arr[] = $somearray[$i]->getjsondata();
}

header("Content-Type: application/json", true);
echo json_encode($arr);

这将输出对象数组的 JSON 表示,例如:

[
    {
        "student_id": 68,
        "student_name": "Jon Smith"
    },
    {
        "student_id": 35,
        "student_name": "Jon Doe"
    },
    {
        "student_id": 65,
        "student_name": "Jim Tim"
    },
    {
        "student_id": 60,
        "student_name": "Jonny Smith"
    }
]
于 2013-10-22T16:21:36.200 回答