如何将这个php数组转换为JavaScript对象数组

How do I convert this php array into a JavaScript array of objects?

本文关键字:数组 转换 JavaScript 对象 php      更新时间:2023-09-26

我在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");
   });