我有一个创建.json文件的PHP:
<?php
$data=array( "Name"=>"Someone", "Surname" => "Somebody");
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{objectValue: '".addslashes($key)."', textObject: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1);
$jsontext .= "]";
echo $jsontext;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsontext));
fclose($fp);
&GT;
这是results.json:
"[{objectValue: 'Name', textObject: 'Someone'},{objectValue: 'Surname', textObject: 'Somebody'}]"
javascript:
var xmlHttp = createXmlHttpRequestObject();
var finalText;
window.onload = process;
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("Cant create XmlHTTP...");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", "http://localhost/results.json", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
//setTimeout('process()', 1000);
alert("Error: Server is busy");
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
finalText = xmlHttp.responseText;
}else{
//alert("Error: server is busy");
}
}
function convertJSON(){
parsedText = JSON.parse(finalText);
alert(parsedText); //This shows the parsed text, it gets here
document.getElementById('finalResult').innerHTML += parsedText.objectValue;
document.getElementById('finalResult').innerHTML += parsedText.Name;
}
每当我从onclick按钮召唤convertJSON时,我都会将结果打印到&#34; finalResult&#34; div ...我做错了什么?
答案 0 :(得分:3)
您正在通过字符串连接构建JSON,然后将其发送到json_encode。而是将您的JSON构建为数组:
$jsonData = array();
foreach($data as $key => $value) {
$jsonData[] = array('objectValue' => $key, 'textObject' => $value);
}
$jsontext = json_encode($jsonData);
echo $jsontext;
fwrite($fp, $jsontext);
答案 1 :(得分:0)
您需要使用有效的JSON,字符串始终用双引号括起来,对象键也用双引号括起来。因此,由PHP提供的JSON字符串应如下所示:
[{"objectValue":"Name","textObject":"Someone"},{"objectValue":"Surname","textObject":"Somebody"}]
您可能希望阅读JSON structure的良好在线参考资料。