1

我有这个 php 代码将结果传递给无法正常工作的 jquery getJSON 函数。

这是我的代码:

    $data["total"]=mysql_num_rows($s);
    while ($r = mysql_fetch_array($s))
    {

        $ris_sql["utente"]=tv($r["utente"]);
        $ris_sql["contratto"]=tv($r["contratto"]);
        $ris_sql["login"]=tv($r["login"]);
        $ris_sql["piattaforma"]=tv($r["piattaforma"]);
        $ris_sql["azione"]=tv(format_valid($r["azione"]));
        $ris_sql["data"]=tv($r["data"]);
        $ris_sql["note"]=tv(str_replace("<br>","",$r["note"]));
        $riga[]=$ris_sql;
    }
    $data["rows"]=json_encode($riga, JSON_FORCE_OBJECT);
    echo json_encode($data);

如果我尝试使用 firebug,我会看到JSON 中的元素结果像字符串而不是一系列对象,我的代码有什么问题?

4

1 回答 1

0

$riga您正在对JSON进行双重编码。在对要发送回浏览器$riga的数组的其余部分进行编码之前,不要单独对该部分进行编码。$data

// Instead of
$data["rows"] = json_encode($riga, JSON_FORCE_OBJECT);
// This double-encodes the contents of $data before outputting back to the browser or ajax call
echo json_encode($data);

// Just do:
echo json_encode($data, JSON_FORCE_OBJECT);

如果格式不是您所期望的,那么您可以将$riga数组转换为 an object,然后在没有JSON_FORCE_OBJECT.

// Cast $riga from an assoc array to an instance of stdClass
$data['rows'] = (object)$riga;
// And then JSON encode the whole $data
echo json_encode($data);
于 2012-04-20T18:32:04.157 回答