[英]Cannot parse JSON returned from PHP
In PHP, I have an Array of JSON Strings I need to return to JavaScript via an AJAX call. 在PHP中,我有一个JSON字符串数组,我需要通过AJAX调用返回到JavaScript。 If I only have one element in the Array, I am able to call JSON.parse() on the response. 如果数组中只有一个元素,则可以在响应上调用JSON.parse()。
Ex (PHP): 前(PHP):
$data = [];
array_push($data, '{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}');
echo json_encode($data);
Ex (JavaScript): 前(JavaScript):
data = JSON.parse(data);
Yields the following, which I can further process and display: 产生以下内容,我可以对其进行进一步处理和显示:
["{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}"]
However, if I push two Elements to the Array: 但是,如果我将两个Elements推入数组:
$data = [];
array_push($data, '{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}');
array_push($data, '{"Date" : "12/12/2015", "Number" : "456", "Status" : "Processing"}');
echo json_encode($data);
I get the following in the Response: 我在响应中得到以下内容:
["{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}",
"{"Date" : "12/12/2015", "Number" : "456", "Status" : "Processing"}"]
When I try and JSON.parse() that, I'm blowing up on the double-quotes around the comma separating the two Elements. 当我尝试使用JSON.parse()时,我用逗号将两个元素分隔开来引起了双引号。
}", "{
I've tried to address this in the PHP by encoding/decoding the Array/String(s) before sending the Response back, but had no luck. 我曾尝试通过在发送回响应之前对数组/字符串进行编码/解码来解决PHP中的此问题,但是没有运气。 I also tried to address this in the JS by calling JSON.stringify() to try and reformat the Response, but no luck there either. 我还尝试通过调用JSON.stringify()来尝试重新格式化Response,以解决JS中的问题,但也没有运气。
Wondering if anyone know the proper encode/decode/parse/stringify pattern to use. 想知道是否有人知道要使用的正确编码/解码/解析/字符串化模式。
Thanks for any input on this! 感谢您对此的任何投入!
You have to populate array
correctly before converting to JSON
with PHP
您必须正确填充array
,然后才能使用PHP
转换为JSON
$data = array();
$data = [];
array_push($data,
array( "Date" => "11/11/2015",
"Number" => "123",
"Status" => "Order Received"
));
echo json_encode($data);
This will give you following output: 这将为您提供以下输出:
[{"Date":"11\/11\/2015","Number":"123","Status":"Order Received"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.