2013-03-15 48 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