我在php中创建了一个数组(作为ajax响应的一部分)。我现在想将此数组转换为javascript对象数组。我该怎么办呢?
我的php数组(请不要这是wordpress php):
$fortot2 = 5;
$fortot3 = 2;
if (is_numeric($numwelds) && is_numeric($numconwelds))
{
$total['tot1'] = $numwelds + $numconwelds + $mpcountrys ;
$total['tot2'] = $numwelds + $numconwelds + $fortot2 ;
$total['tot3'] = ($numwelds + $numconwelds) + $fortot2 / $fortot3;
$response = json_encode($total);
header("Content-Type: application/json");
echo $response;
现在,一旦json被编码,如何将其转换为javascript对象数组?
答案 0 :(得分:2)
// responseData is fetched via Ajax-Get
var obj = jQuery.parseJSON(responseData);
alert(obj.property);
// full ajax example
jQuery.ajax({
url: "/index.php?action=whereMyDataIs", // here php gives the json response
type: "GET",
dataType: "json",
async: false,
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
}
});
你已经拥有PHP部分(数组是构建,json_encoded并作为响应发送),下一步是通过对提供响应的PHP脚本执行ajax get请求,在客户端获取此json_response。通过指定dataType:" json"你告诉jQuery自动将传入的数据解析为Object Notation。如果要再次输出,例如有警报,你需要再次对其进行字符串化。
回答有关amcharts的问题:
// add the loadJson function to AmCharts
// but you could also use jQuery as demonstrated above
AmCharts.loadJSON = function(url) {
// create the request
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET', url, false);
request.send();
// parse adn return the output
return eval(request.responseText);
};
// init chart library
var chart;
// lets build that chart
AmCharts.ready(function() {
// load the data from your php script (the json response)
var chartData = AmCharts.loadJSON('script.php');
// verify in browser console, if the data is loaded and parsed correctly
console.log(chartData);
// build the chart
// ...
// output the chart
chart.write("chartdiv");
});