javascript - 从 javascript 运行循环以保存在 Mysql 中

标签 javascript mysql

您好,我目前正在我的 php 页面上运行 JavaScript(如下),它会显示我需要的每个数据,有什么方法可以将其连接到 mysql 数据库吗? (我是 JavaScript 新手)

<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 我已经有数据库设置的连接

最佳答案

使用 ajax/json 请求将数据发布到 php 函数,并使用 php 完成所有与数据库相关的工作。接下来返回成功或失败状态,该状态将在这个调用的js函数中捕获,然后您可以使用javascript显示成功或失败消息。

示例:

包含 jQuery 库:

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

使用 jQuery 进行 ajax 请求的脚本:

    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/

关于javascript - 从 javascript 运行循环以保存在 Mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435183/

相关文章:

javascript - 根据 anchor 击更改 InnerHTML

Mysql仅清空选定的一列

mysql - Cakephp 3.x 在多级连接中过滤数组中的行

javascript - 使用 Javascript 函数启动下载

javascript - jQuery 函数,当一个列表项具有事件类时,我希望所有其他列表项自动不具有事件类?

C# Mysqlexecutenonqueryasync不是异步的

mysql - sql bool 真值测试 : zero OR null

php - 为什么我的成员(member) ID 列返回空值?

JavaScript onsubmit 事件不会更新 html 表单操作属性

javascript - 使用照片编辑器 SDK 从 URL 编辑照片