无法使用PHP将数据从javascript保存到MySql

时间:2018-05-23 08:46:12

标签: javascript php mysql ajax xml

我遇到一个问题,我无法将从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();

1 个答案:

答案 0 :(得分:1)

如果您要将数据作为GET参数发送,则必须先对其进行URL编码:

var dbParam = encodeURIComponent(JSON.stringify(data));

然而,我会指出通过GET请求执行写操作是非常糟糕的做法。您将面临各种各样的滥用和跨端脚本攻击。对于初学者,您可以阅读这篇文章,并在Google上进行一些研究:

https://softwareengineering.stackexchange.com/questions/188860/why-shouldnt-a-get-request-change-data-on-the-server