2013-03-15 40 views
0

你好,我目前正在我的PHP頁面(下面)運行一個JavaScript,它出來與我需要的每個數據是有什麼辦法,我可以連接到MySQL數據庫? (我是新來的JavaScript)從JavaScript運行循環保存在Mysql

<script> 
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || []; 
for(var i = 0; i < allItems.length; i++) { 
    var item = allItems[i]; 
    console.log('Current item: %o', item); 

} 
</script> 

'itemsArray來自一個保存功能'

function save(){ 

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; 

var newItem = {}; 
var num = document.getElementById("num").value; 

newItem[num] = { 
    "methv": document.getElementById("methv").value 
    ,'q1': document.getElementById("q1").value, 
    'q2':document.getElementById("q2").value, 
    'q3':document.getElementById("q3").value, 
    'q4':document.getElementById("q4").value, 
    'comm':document.getElementById("comm").value 
}; 


oldItems.push(newItem); 

localStorage.setItem('itemsArray', JSON.stringify(oldItems)); 


}); 

感謝

PS我已經爲數據庫設置了連接

+0

JavaScript的執行在客戶端上。通常,MySQL駐留在服務器上。所以要做到這一點,您必須對服務器執行AJAX請求以存儲/檢索數據。除非這是一個非常奇怪的場景,MySQL將駐留在客戶端機器上,在這種情況下,我不知道JavaScript是否可能,但我猜測事實並非如此。 – Travesty3 2013-03-15 14:42:41

回答

1

發表您的數據與ajax/json請求到一個PHP函數,並做所有數據庫相關的工作與PHP。接下來返回成功或失敗狀態,這將被捕獲在這個被稱爲js函數,然後你可以顯示成功或失敗的信息與JavaScript。

實施例:

包括jQuery庫:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 

腳本對AJAX請求與jQuery:

var path = 'http:/your_url/your_php_script_file.php'; 
    var data = 'json_data=' + JSON.stringify(newItem[num]); 
     $.ajax({ 
      url: path, 
      type: "POST", 
      data: data, 
      cache: false, 
      success: function ($returm_msg){ 
       alert($returm_msg); 
      } 
     }); 

PHP爲保存在數據庫/更新:

$receive_value = json_decode($_POST['json_data'], true)); 

你會 得到像

$receive_value['methv'],$receive_value['q1'],....,$receive_value['comm']; 

現在在數據庫中執行保存操作。

$result = mysql_query("INSERT INTO .....") or die(mysql_error()); 
if($result){ 
    return "Success!"; // if not function then simply echo "Success!"; 
}else{ 
    return "Failure!"; // if not function then simply echo "Failure!"; 
} 

幫助鏈接:

  1. http://www.bennadel.com/resources/presentations/jquery/demo21/index.htm
  2. http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
+0

對不起,我有點新Ajax/Json可以顯示一個例子或鏈接嗎? – user2162768 2013-03-15 14:46:58

+0

瞭解Ajax是什麼以及它如何提供幫助。搜索Ajax,你會發現很多可以學習的資源。此社區不建議鏈接到外部網站 – Amareswar 2013-03-15 15:40:26

+0

我建議不要使用'mysql_ *'函數庫,因爲它已被棄用。 – 2013-03-15 18:36:23