MySQL> JSON,导致URL错误

时间:2009-12-28 22:33:21

标签: php mysql json url encode

我将此代码转换为json:

$sth = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($r = mysql_fetch_array($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

效果很好,但我在我的数据库中有一个url字段,这里是一个示例json行:

{"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"},

我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为“问题”是网址中是否存在反斜杠?

喜欢:

http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg

嗯,这不是Javascript的问题:尝试将您的JSON数据分配给Javascript对象,并显示其中一个URL:

var data = {"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"};
alert(data[3]);

网址显示正确:

http://images.apple.com/webapps/productivity/images/noter2_20091223182720-thumb.jpg

因此,反斜杠不是“问题”; - )


事实上,如果你看一下json.org的“字符串”部分,你会发现斜杠必须被反斜杠才能让你的字符串有效。

答案 1 :(得分:0)

我在这里看不到问题。如果您想知道为什么URL看起来像这样:

http:\/\/www.example.com\/

而不是这样:

http://www.example.com/

这是因为/字符正在被适当地转义。当您在javascript中反序列化JSON对象时,URL将与数据库中的URL一样。