如何将这个php数组转换为JavaScript对象数组
How do I convert this php array into a JavaScript array of objects?
我在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;
现在,我怎么能把它转换成一个javascript数组的对象,一旦json已经编码?
// 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将传入的数据自动解析为对象表示法。如果你想再次输出它,例如使用alert,你需要再次对它进行字符串化。
关于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");
});
相关文章:
- 使用JS将数组转换为json对象
- 本地存储中的字符串到字节数组转换
- Javascript函数,用于将数组转换为“;2-元组”;
- php数组转换为javascript
- 在Javascript中将一个值和字符串数组转换为if语句
- 将数组转换为javascript格式的字符串
- 如何将数组转换为有效的json
- JSON数组转换为JS对象数组
- 如何将数组转换为映射
- JavaScript:将字符串数组转换为文本区域
- javascript |数组转换
- 数组转换为多个字符串
- Javascript将数组转换为字符串并使其反向输出
- 将Byte数组转换为Angularjs中的Base64字符串
- 将对象数组转换为与nodejs/pg/unnest兼容的数组
- 将Javascript数组转换为PHP数组
- 将数组转换为键值对
- 使用Ramda将对象数组转换为普通对象
- javascript将对象数组转换为字符串以存储在s3中
- 使用.join方法将数组转换为不带逗号的字符串