1

我知道这已经被问了一百万次,但它对我不起作用。我有一个 PHP 脚本(get_pathway_allowed.php),它在硬编码时输出以下 json 格式

{"pathway_allowed":"n","comment":"one comment"}{"pathway_allowed":"y","comment":"comment two"}{"pathway_allowed":"n","comment":"comment three"}{"pathway_allowed":"n","comment":"comment four"}

阿贾克斯脚本:

$('.pathway_button').click(function() { 
alert(caseId + ' ' + currentLevel);
$.ajax({
       type: "POST",
       url: "scripts/get_pathway_allowed.php",
       data: {case_id: caseId, level: currentLevel};
       dataType: "json",
       cache: false,
       success: function(response) {
            alert(response[0].pathway_allowed);

    }
});
});

现在alert(caseId + ' ' + currentLevel);显示两个变量的正确初始值。但是成功后我没有看到警报。如果我删除dataType: "json",,我会看到未定义值的成功警报(预期......)。

get_pathway_allowed.php 有:

$case = $_POST['case_id'];
$level = $_POST['level'];

$query = "SELECT * FROM pathway WHERE level = '$level' AND case_fk = '$case'";
$result = mysql_query($query, $connection) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
        $caseData = array(
        'pathway_allowed' =>  $row['pathway_allowed'],
        'comment' =>  $row['comment']
        );

print json_encode($caseData);
} 

正如我之前所说,硬编码:

$case = '10';
$level = '1';

输出json数据如上OK。我究竟做错了什么?

4

3 回答 3

2

JSON字符串的创建是错误的,使用:

$caseData=array();
while ($row = mysql_fetch_array($result)) {
        $caseData[] = array(
        'pathway_allowed' =>  $row['pathway_allowed'],
        'comment' =>  $row['comment']
        );

} 

print json_encode($caseData);

另外还有一个语法错误:

data: {case_id: caseId, level: currentLevel};
//------------------------------------------^

分号必须是逗号

于 2013-07-26T08:00:20.237 回答
1

修复您的 JSON 字符串:

{ "values": [
    {"pathway_allowed":"n","comment":"one comment"},
    {"pathway_allowed":"y","comment":"comment two"},
    {"pathway_allowed":"n","comment":"comment three"},
    {"pathway_allowed":"n","comment":"comment four"}]
}
于 2013-07-26T07:55:50.707 回答
1

您的 json 无效,它应该如下所示:

{
    "data": [
        {
            "pathway_allowed": "n",
            "comment": "one comment"
        },
        {
            "pathway_allowed": "y",
            "comment": "comment two"
        },
        {
            "pathway_allowed": "n",
            "comment": "comment three"
        },
        {
            "pathway_allowed": "n",
            "comment": "comment four"
        }
    ]
}

使用jsonlint来验证你的 json。

于 2013-07-26T07:55:59.893 回答