2017-04-18 42 views
-1

我試圖編寫自己的第一個Web應用程序。服務器和客戶端之間的數據交換應通過使用AJAX來建立。首先,我打算給userinput(HTML形式)從客戶端轉移到這個服務器端JS - 摘錄:使用AJAX將PHP數組轉換爲Javascript

$("#submit").on("click", function(e) { 
    e.preventDefault(); 

    $.ajax({    
     url : "ajax.php", 
     type : "POST", 
     data : $("#nodes").serialize(), 
     dataType: "text", 
     cache : false, 
     success: function(data) { 
      console.log(data); 
      $("#ajaxrequest").html(data); 
     }, 
     error: function(xhr, desc, err) { 
      console.log(xhr); 
      console.log("Details: " + desc + "\nERROR: "+ err); 
     } 
    }); 
}); 

它的工作......但現在我想上手三種不同的數據(PHP- )從我的服務器陣列到客戶端用:

<?php 

echo json_encode($currentdata); 
echo json_encode($maxmindata); 
echo json_encode($chartdata); 

我想知道的是,陣列中的console.log所示,直到我regonized data: $("#nodes").serialize(),包含所有傳輸的數據。當然,我需要在我的JS文件中提取不同變量中的所有三個數組。

我想是這樣

success: function(data) { 
      console.log(data); 
      current = data.currentdata; 
} 
當然,沒有工作的

...

這是控制檯輸出:

> {"max":{"temperature":"21.14","humidity":"39.96","pressure":"1022.2"},"min":{"temperature":"21.08","humidity":"38.72","pressure":"1022.0"}}{"current":{"ID":"755","temperature":"21.43","humidity":"40.09","pressure":"1022.8","voltage":"3.337","datetime":"2017-04-18 
> 20:46:31"}}[{"ID":"570","nodeId":"Node1","humidity":"38.83","temperature":"21.08","pressure":"1022.2","voltage":"3.323","datetime":"2017-04-18 
> 20:00:02"},{"ID":"571","nodeId":"Node1","humidity":"38.72","temperature":"21.08","pressure":"1022.1","voltage":"3.321","datetime":"2017-04-18 
> 20:00:17"},{"ID":"572","nodeId":"Node1","humidity":"38.84","temperature":"21.1","pressure":"1022.1","voltage":"3.321","datetime":"2017-04-18 
> 20:00:32"}, 

如果你沒有得到我想要的問:如何將不同的PHP數組分配給不同的JS變量?我需要編寫另一個$ .ajax嗎?

+3

創建數組的數組。 –

+0

那麼,這個評論什麼都沒有幫助。 –

+0

您正在一個接一個地發送3個數組對象。例如:在你的控制檯上你有'..}} [{..'。創建一個包含你的3個數組的新數組並返回這個數組。 – Arthur

回答

1

好的,如果評論沒有幫助,這是一個答案。

與您的所有值創建數組:

<?php 
$result_array = array(
    'current_data' => $currentdata, 
    'max_min_data' => $maxmindata, 
    'chart_data' => $chartdata, 
); 

echo json_encode($result_array); 

而且修改您的JS:

$.ajax({    
    url : "ajax.php", 
    type : "POST", 
    data : $("#nodes").serialize(), 
    // set dataType as `json`, this will create json object from response automatically 
    dataType: "json", 
    cache : false, 
    success: function(data) { 
     console.log(data); 
     console.log(data.current_data); // key is the same as in php array 
     //$("#ajaxrequest").html(data); 
    }, 
    error: function(xhr, desc, err) { 
     console.log(xhr); 
     console.log("Details: " + desc + "\nERROR: "+ err); 
    } 
}); 
+0

謝謝! @AndreiGheorghiu自兩週以來,我正在學習JS和PHP。我花了將近一天的時間解決這個問題,所以請不要責怪我的不知情! –

+0

好的,@NiclasResse。我會承擔責任。開玩笑說,當有人告訴你該做什麼時,你不要回答「這沒有幫助」。你至少可以做的是感謝和(重新)搜索。 –

+0

是的,@AndreiGheorghiu我同意你的看法,但是如果你花了很多時間去解決一些愚蠢的問題,並且沒有解決方案,那麼應該允許在stackoverflow中提出一個問題。 –