jQuery AJAX .done没有为JSON数据触发

时间:2013-10-22 16:13:22

标签: php jquery ajax json

出于某种原因,在成功进行AJAX调用后,.done()函数未触发。这是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;
    }

1 个答案:

答案 0 :(得分: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"
    }
]
相关问题