首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将这个php数组转换为对象的JavaScript数组?

问如何将这个php数组转换为对象的JavaScript数组?
EN

Stack Overflow用户
提问于 2014-03-28 23:24:56
回答 1查看 362关注 0票数 1

我在php中创建了一个数组(作为ajax响应的一部分)。现在,我想将这个数组转换为对象的javascript数组。请问我怎么做?

我的php数组(请不要,这是wordpress php):

代码语言:javascript
复制
$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数组?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-28 23:28:14

代码语言:javascript
复制
// 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));
    }
});

您已经有了part (数组是build、json_encoded和send ),下一步是通过对提供响应的PHP脚本执行ajax请求,在客户端获取这个json_response。通过指定dataType:"json“,可以告诉jQuery将传入的数据自动解析为对象表示法。如果您想要再次输出它,例如,以警报,您需要再次紧张它。

为回答有关图表的问题:

代码语言:javascript
复制
// 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");
   });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22724891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档