您好,我目前正在我的 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!";
}
有用的链接:
关于javascript - 从 javascript 运行循环以保存在 Mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435183/