使用AJAX将JSON转换为PHP


JSON to PHP with AJAX

我想将一个JSON字符串发送到一个包含一些用户信息的PHP文件,然后将该信息插入MySQL数据库。

我的HTML:

<!DOCTYPE html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <form name="form1" action="" onSubmit="sub()">
        <input type="text" name="username" id="usrnm" />
        <input type="text" name="password" id="pswrd" />
        <input type="text" name="firstname" id="frstnm" />
        <input type="text" name="surname" id="surnm" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

script.js:中的我的Javascript

function sub() {
        var un = document.getElementById("usrnm").value;
        var pw = document.getElementById("pswrd").value;
        var fn = document.getElementById("frstnm").value;
        var sn = document.getElementById("surnm").value;
        var jsonObj = {username:un, password:pw, firstName:fn, surName:sn};
        var xmlhttp = new XMLHttpRequest();     
        xmlhttp.open("POST","server.php" ,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("data="+encodeURIComponent(JSON.stringify(jsonObj)));
    };

我的PHP:

<?php 
    $con=mysqli_connect("localhost","root","", "somedatabase");
    $data = $_POST["data"];
    $res = json_decode($data, true);
    mysqli_query($con,"INSERT INTO sometable (username,password,firstname,surname) VALUES ($res[username],$res[password],$res[firstname],$res[surname])");
    mysqli_close($con);
?>

当我用普通字符串值替换insert语句中的值时,我的PHP会在DB中插入一个新行,但当我尝试使用PHP对象中的值的时候,不会插入任何内容。

让它像一样

VALUES (" . $res['username'] . "," . $res['password'] . "," . $res['firstname'] . "," . $res['surname']. ")"

而不是直接在字符串中。PHP不会接受这一点。

使用文本作为键的数组应该始终被引用。例如$array_name['key']

因此,请尝试将查询行更改为

mysqli_query($con,"INSERT INTO sometable (username,password,firstname,surname) VALUES ($res['username'],$res['password'],$res['firstname'],$res['surname'])");

如果您仍然有问题,请尝试测试$res 的结果

print_r($res);