0

嗨,我有一个页面包含一个链接,当用户单击该链接时,我想去数据库并检索两个数组,但是当我提醒这两个数组时,我得到了这个异常

Unexpected token [

这是我的js代码

function acNewConcpet(element){
    var parent = element.parentNode;
    parent.removeChild(element);
    var concpetSelect = document.createElement('select');
    var relationSelect = document.createElement('select');
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 &&  xmlhttp.status==200){
            var data = JSON.parse(xmlhttp.responseText);
            alert(data);
        }

    }
    xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+"concept"+"/TRUE",true);
    xmlhttp.send();
}

这是我的 php 代码

public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
        if ($Ajax) {
            $concepts = array('c1', 'c2');
            $relations = array('r1','r2');
            echo json_encode($concepts);
            echo json_encode($relations);
        }
        return;
}

为什么这个例外?我该如何解决?以及如何在我的 js 中接收这两个数组?这是完整的代码

4

3 回答 3

3

JSON.parse只能解析单个JSON 文字。

您应该将这两个数组组合成一个具有两个属性的对象。

于 2012-05-13T21:50:14.687 回答
3

您正在返回格式错误的 JSON。根据我从您的代码中了解到的情况,它会打印出这个 JSON:

['c1','c2']['r1,r2']

你不能有 2 个这样的数组。你必须像这样打印它:

[['c1','c2'],['r1','r2']]

对不起我生锈的 PHP,但你必须有类似的东西:

$json = array(
    array('c1','c2'),
    array('r1','r2')
);

echo json_encode($json);

既然您使用的是 jQuery,为什么不使用$.getJSON()?

$.getJSON(url,function(returnData){
    //returnData is the parsed JSON
});
于 2012-05-13T21:51:11.927 回答
1

当您响应 JSON 时,它必须是一个 JSON,但您发送的是两个单独的数组。

将这两个 JSON 合并为一个。

更新:

像这样做:

public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
    if ($Ajax) {
        $concepts = array('c1', 'c2');
        $relations = array('r1','r2');
        echo json_encode(array($concepts, $relations));
    }
    return;
}
于 2012-05-13T21:50:49.243 回答