[英]Display JSON data in a PHP page
I have a PHP page that will return JSON data as output. 我有一个PHP页面,它将返回JSON数据作为输出。 I get the data as AJAX.
我得到的数据为AJAX。 I want to display the results from JSON.
我想显示JSON的结果。 But when I try to display each value I am getting undefined error.
但是,当我尝试显示每个值时,我得到了未定义的错误。
This is the PHP code for getting data: 这是获取数据的PHP代码:
if (isset($_POST['dcqid'])) {
$question_id = intval($_POST['dcqid']);
if ($question_id != "") {
$user_id = $session->id;
$questiondetail = getData("dcquestions", "dcqid", "dcqid", $question_id, "", "");
//print_r($questiondetail);
echo json_encode($questiondetail);
?>
}
}
This is the JSON output I am getting 这是我得到的JSON输出
[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}]
This is the AJAX code I am using to display data 这是我用来显示数据的AJAX代码
<script type="text/javascript">
$(".edit-current").on('click', function (e) {
e.preventDefault();
var id = $(this).data('currentid');
alert(id);
var url = "<?php SITE_URL ?>admin/" + "admin_edit_current.php";
var info = 'dcqid=' + id;
$.ajax({
type: "POST",
url: url,
data: info,
success: function (data) {
console.log(data);
console.log(data.dcqid); // undefined
},
error: function (data) {
alert(data.responseText);
alert("Error occured in showing details");
}
})
});
</script>
I am currently getting undefined for the values I want to display. 我目前对要显示的值不确定。
Its because the data var is an array. 这是因为数据var是一个数组。 it's like this:
就像这样:
data = [
{
dcqid : 123
}
]
so try using 所以尝试使用
console.log(data[0].dcqid)
1st : Access it like this 1st:像这样访问
console.log(data[0].dcqid);
2nd : Add dataType
in ajax 第二个:在ajax中添加
dataType
dataType:"json"
Note : your value is inside the 0th
index . 注意:您的值在第
0th
索引内。 so you need to access it like above. 因此您需要像上面一样访问它。
var data =[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}]; console.log(data[0].dcqid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.