I want get a json array from PHP with jQuery, but it is not working.
我想从PHP中得到一个json数组,但它不起作用。
PHP
PHP
$json[] = array(
'status' => 'no',
'xxx' => $myhtml
);
echo json_encode($json);
$myhtml
is HTML source.
美元myhtml HTML源代码。
jQuery
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.
我在控制台有一个json数组,但是json。xxx是未定义的。
2 个解决方案
#1
1
Use JSON.stringify()
, the php
code is also modified, i.e.:
使用JSON.stringify(), php代码也被修改,即:
html:
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:
<?php
header('Content-Type: application/json');
$myhtml = '<p> TEST </p>';
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
echo json_encode($json);
#2
1
You are creating an extra outer array.
您正在创建一个额外的外部数组。
Your current JSON would look like:
您当前的JSON是:
[
{"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:
但是将php更改为:
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
which when json encoded would produce:
当json编码时会产生:
{"status" : "no", "xxx" : "html string"}
#1
1
Use JSON.stringify()
, the php
code is also modified, i.e.:
使用JSON.stringify(), php代码也被修改,即:
html:
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:
<?php
header('Content-Type: application/json');
$myhtml = '<p> TEST </p>';
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
echo json_encode($json);
#2
1
You are creating an extra outer array.
您正在创建一个额外的外部数组。
Your current JSON would look like:
您当前的JSON是:
[
{"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:
但是将php更改为:
$json = array(
'status' => 'no',
'xxx' => $myhtml
);
which when json encoded would produce:
当json编码时会产生:
{"status" : "no", "xxx" : "html string"}