我在我的数据库上使用mysql查询并在我的php脚本中使用fetch_array()函数构建行数组并将其转换为json。现在在我的ajax成功代码中可以看到我的控制台日志中的行如下所示
" {" 0":" 84"" ID":" 84"" 1&# 34;:" BTV"" news_name":" BTV"" 2":" BTV"&# 34; news_title":" BTV"" 3":"孟加拉 Televesion"" news_description":"孟加拉 Televesion"" 4":" /management/template/img/default_logo.png"," news_logo":" /管理/模板/ IMG / default_logo.png"" 5":"达卡 孟加拉国"" news_address":"达卡 孟加拉国"" 6":"自由"" subs_status":"自由"" 7&#34 ;: " 33"" newscreatedbyID":" 33"" 8":" 2014年8月21日",& #34; newscreateddate":" 2014年8月21日"" 9":空,"赞助":空," 10&#34 ;:" 0"" protectstatus":" 0"" 11":" 0"&#34 ;批":" 0"}"
我的js成功功能如下:
$.ajax({
url: "/function/news_user_page.php",
type: "POST",
data: {news_name:'84'},
success:function(data, textStatus, jqXHR)
{
$("#test").html(data.news_title);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
})
我可以在我的consol日志中看到整个数据,但是在名为test的html元素中,news_title现在正在显示。 data.news_title无效。如何访问我转换的json数据?我有点困惑。
答案 0 :(得分:3)
看起来你有一个字符串版本,在你的AJAX请求中设置dataType
以自动将其转换为JSON:
dataType: "JSON",
或者,在回复中使用JSON.parse
var parsed = JSON.parse(data);
答案 1 :(得分:2)
尝试将dataType设置为json
答案 2 :(得分:0)
回显数据只会返回一个字符串。请改用echo json_encode( $data );
。
以下是您可以在PHP中执行的操作,以确保从您的服务器发送json:
<?PHP
$data = /** whatever you're serializing --- array/object **/;
header('Content-Type: application/json');
echo json_encode($data);