我正在学习 JSON。我已经四处阅读以找到解决我可能做错的方法,但我真的找不到它。我正在尝试将 JSON strnig 传递给 PHP 并查看它返回的内容......无论我做什么,我当前的代码总是返回 null。我觉得我正在尽一切努力让它发挥作用。但显然我一定错过了什么
谁能告诉我为什么$arrayData
总是返回NULL
?
我可以看到当前发布的是mydata=%7B%22name%22%3A%22yes%22%2C%22regno%22%3A%22hola%22%7D
如果我不使用JSON.stringify()
,那么我会看到数据发送为mydata=[object Object]
PHP
<?php
$mydata = $_POST['mydata'];
$arrayData = json_decode($mydata);
var_dump($arrayData);
?>
HTML
<script>
function lol () {
var name = "yes";
var regno = "hola";
var arrayData = {"name":name,"regno":regno};
console.log(arrayData);
$.ajax({
url: "algo2.php"
,type: "POST"
,headers: {'Content-Type': 'application/json',}
,data: {'mydata=' : JSON.stringify(arrayData)}
,success : function(response) {
alert(response);
}
,error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
}
</script>
</head>
<button onclick="lol()">Try it</button>
选项 2
function lol () {
var name = "yes";
var regno = "hola";
var arrayData = {"name":name,"regno":regno};
console.log(arrayData);
console.log(JSON.stringify(arrayData));
$.ajax({
url: "algo2.php"
,type: "POST"
,data: 'mydata=' + arrayData
,success : function(response) {
alert(response);
}
,error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
}