2014-03-28 100 views
1

我在php中創建了一個數組(作爲ajax響應的一部分)。我現在想將這個數組轉換成一個javascript數組對象。我該怎麼做?如何將此php數組轉換爲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已經被編碼?

+0

你跟阿賈克斯獲得此爲有頭和一切? – adeneo

+0

是的,這是我的ajax的迴應。這些變量被加起來創建ajax中的總數。現在我想把這3個總數放在我放入的數組中,並將它們轉換爲js數組對象。 – mattnewbie

回答

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和發送的響應),接下來是你取的客戶端這json_response,通過做一個AJAX GET請求到PHP腳本提供響應。通過指定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"); 
    }); 
+0

瞭解你!你需要使用JSON - 是的,你已經使用了'$ response = json_encode($ total);'和'header(「Content-Type:application/json」);'。你寫,你需要它的一個Ajax請求。我認爲你瞭解JSON結果。你可以用'JSON.parse()'將它轉換成javascript。但是你的直接問題是什麼? jQuery示例是一個**示例**。學習實現項目的基礎知識。 –

+0

請相處愉快。我們都是以初學者開始的。 –

+0

@ Jens-AndréKoch謝謝。對於基本問題抱歉。所以,我可以使用'jQuery.parseJSON'將它轉換爲像這樣的對象JavaScript數組。謝謝 – mattnewbie