我正在尝试将JSON数据从Javascript Ajax解析为PHP,我在控制台中收到错误消息。如何将json编码为字符串格式。我做错了什么,这是我的附加代码。
function datasend(obj)
{
var flickr = {"name": "vivek", "age":"18"};
var data = JSON.stringify(flickr);
alert(data);
var request = new XMLHttpRequest();
request.open("POST", "getvalue.php", true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
// Success!
alert("yes");
var resp = request.responseText;
document.getElementById("sum").innerHTML=resp;
}
}
request.send(data);
}
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$getnme=$json_decode->{'name'};
$json_response = json_encode($json_decode);
echo $getnme;
include 'db.php';
$sql= "UPDATE user1 SET name='".$getnme."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
?>
我想通过更新查询将我的名字发送到数据库,这里我在解码json数据后没有得到我的名字。
答案 0 :(得分:1)
试试这种方式
写一个$getnme=$json_decode['name'];
而不是$getnme=$json_decode->{'name'};
答案 1 :(得分:-1)
var request = new XMLHttpRequest();
request.open("POST", "getvalue.php", true);
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/JSON");
xhttp.send(JSON.stringify({"name": "vivek", "age":"18"}));
并在php方面
<?php
$obj = json_decode($json);
$getnme= $obj->name;
echo $getnme;
?>