簡體   English   中英

將$ get結果字符串轉換為javascript數組

[英]Turn $get result string into javascript array

我正在尋找使用jqplot插件( http://www.jqplot.com/tests/pie-donut-charts.php )來生成餅圖,但是我很難從$ get函數獲取結果jqplot函數將可接受的數據。

您可以在上面的jqplot鏈接中看到如何創建顯示餅圖的數據變量。

這是我的$ .get函數,當前返回一個字符串:

//data is returned as a string: 'some_field_name',10,'some_other_field,33 etc
$.get("notesajax.php", {month:monthFilter, area:areaFilter}, function(data) {
    var arr = data.split(",");
    var results = [];
    for (var i = 0; i < arr.length; i++) {
        mini = [];
        mini[arr[i]] = "'"+arr[i]+"',"+arr[i+1];
        results.push(mini);
        i++;
    }

為了便於參考,這里是jqplot函數,該函數在開始時包括一個已定義的“ data”變量,以說明jqplot期望如何接收數據。

//this variable is just for illustrative purposes
var data = [
    ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14], 
    ['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];

var plot1 = jQuery.jqplot ('chartdiv', [results], 
    { 
        seriesDefaults: 
        {
            // Make this a pie chart.
            renderer: jQuery.jqplot.PieRenderer, 
            rendererOptions: {
                // Put data labels on the pie slices.
                // By default, labels show the percentage of the slice.
                showDataLabels: true
            }
        }, 
        legend: { show:true, location: 'e' }
    }
);

但是到目前為止,我無法將$ get返回的數據轉換成jqplot函數可以接受的格式。

var field, value, data = [], str = "'some_field_name',10,'some_other_field,33";
var arr = str.split(',');
// just add 2 to each iteration to get every second item (last argument is i += 2):
for (var i = 0; i < arr.length; i += 2) {
  field = arr[i].replace(/'/g, ""); // replace ', because otherwise your string will be "'some_field_name'"
  value = parseInt(arr[i+1], 10); // parseInt because you want numbers, but got a string
  data.push([field, value]); // push into your data-array an array with your field and value
}

jsfiddle在這里: http//jsfiddle.net/wLxyZ/

您正在生成錯誤的數組。 您應該直接從服務器發送回JSON對象(建議這樣做既簡單又方便),或者使解析腳本正常運行。

$.get("notesajax.php", {month:monthFilter, area:areaFilter}, function(data) {
var arr = data.split(",");
var results = [];
for (var i = 0; i < arr.length; i++) {
    var mini = new Array();
    mini.push(arr[i]);
    mini.push(arr[i+1]);
    results.push(mini);
}

我玩過您的代碼,並提出以下解決方案,您的原始代碼存在一些問題,尤其是關於如何構造迷你數組的問題

var arr = ['some_field_name',10,'some_other_field',33];
var results = [];
for (var i = 0; i < arr.length; i+=2) {        
    var mini = ["'"+arr[i]+"'",+arr[i+1]];
    results.push(mini);
}
alert(results[0][0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM