【发布时间】:2017-03-12 20:06:39
【问题描述】:
我尝试将其转换为 json 数组并将 json 字符串解析为 MySQL,因为这对我来说最有意义。另外,我已经设法使用以下方法将其转换为 json 字符串:
JSON.stringify(res);
这是正确的方法吗?如何将 x、y、宽度和高度添加到 MySQL 中?我认为问题在于我无法在 PHP 脚本中读取 Javascript 变量。
$('#save').click(function(){
var res = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var node = el.data('_gridstack_node');
return {
id: el.attr('data-custom-id'),
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
window.location.href = "index.php?name=" + JSON.stringify(res);
<?php
if (isset($_GET['name'])) {
$con = mysqli_connect("localhost", "root", "", "grids");
$jsondata = $_GET['name'] ;
$data = json_decode($jsondata, true);
$x = $data['x'];
$y = $data['y'];
$width = $data['width'];
$height = $data['height'];
foreach($data as $row){
$sql = "INSERT INTO new(x, y, width, height) VALUES('".$row[$x]."', '".$row[$y]."', '".$row[$width]."', '".$row[$height]."')";
mysqli_query($con, $sql);
}
}
?>
});
【问题讨论】:
-
这一切都在
index.php中吗?如果是这样,那么您将 JSON 发送为name=,但将其读取为work。您还应该使用准备好的语句。 -
对不起,在我的代码中它都被称为“名称”。使用准备好的语句会修复我的错误吗?
-
它将修复任何未转义的参数相关错误(例如,如果任何这些参数中有引号)。它还将保护您免受自动 SQL 注入攻击。您可能还需要
encodeURI(JSON.stringify(res))才能将其正确传递给 PHP。你的意思是在click事件中包含重定向?
标签: javascript php mysql json