Reputation: 155
I want get a json array from PHP with jQuery, but it is not working.
PHP
$json[] = array(
'status' => 'no',
'xxx' => $myhtml
);
echo json_encode($json);
$myhtml
is HTML source.
jQuery
$.post('server.php', {'work' : work , 'view_id' : view_id } , function(data){
var json = JSON.parse(data);
$('#main-show').html(json.xxx);
});
I have array json in console, but json.xxx is undefined.
Upvotes: 1
Views: 970
Reputation: 98861
Use JSON.stringify()
, the php
code is also modified, i.e.:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<div id="main-show"></div>
<script>
work = "test";
view_id = "test2";
$.post('json.php', {'work' : work , 'view_id' : view_id } , function(data){
var json = JSON.parse(JSON.stringify(data));
$('#main-show').html(json.xxx);
});
</script>
</body>
</html>
php:
<?php
header('Content-Type: application/json');
$myhtml = '<p> TEST </p>';
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
echo json_encode($json);
Upvotes: 1
Reputation: 171679
You are creating an extra outer array.
Your current JSON would look like:
[
{"status" : "no", "xxx" : "html string"}
]
So to access that would need
$('#main-show').html(json[0].xxx);
But it would probably be easier to change php to:
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
which when json encoded would produce:
{"status" : "no", "xxx" : "html string"}
Upvotes: 1