我遇到一个问题,我无法将从Javascript解析的数据保存到PHP中。当我实现WordPress时出现问题。在单个index.html上,它正在工作,数据能够存储在数据库中。
在Javascript文件上:(发送数据)
var dbParam = JSON.stringify(data);
console.log(dbParam);
var obj, dbParam, xxmlhttp;
xxmlhttp = new XMLHttpRequest();
xxmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("demo").innerHTML = this.responseText;
}
};
xxmlhttp.open("GET", "http://localhost/trackpage/dummy-data/saveDB.php?x=" + dbParam, true);
xxmlhttp.send();
console.log("send");
在PHP文件上:(获取数据)
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli ("localhost", "root", "", "laravelcrudwebapp");
$stmt = $conn->prepare("INSERT INTO tracks (data1,data2) VALUES (?, ?, )");
$stmt->bind_param("ss",$obj->data1,$obj->data2);
$stmt->execute();
$stmt->close();
$conn->close();
答案 0 :(得分:1)
如果您要将数据作为GET参数发送,则必须先对其进行URL编码:
var dbParam = encodeURIComponent(JSON.stringify(data));
然而,我会指出通过GET请求执行写操作是非常糟糕的做法。您将面临各种各样的滥用和跨端脚本攻击。对于初学者,您可以阅读这篇文章,并在Google上进行一些研究: