![](/img/trans.png)
[英]From an ajax json request, how can dynamically add the objects to an array so that I can loop through them?
[英]how can i acces the JSON data of POST request sent through ajax to a php file and store them in an array variable?
我通过ajax将json数据发送到一个名为'receive.php'的php文件。
user_name
、 user_id
等在我的脚本页面顶部定义,您可以通过其他任何方式进行更改。
这是我的 js 代码:
const data = {
name: user_name,
id: user_id,
score: success,
time: endTime
};
const jsonString = JSON.stringify(data);
const xhr = new XMLHttpRequest();
xhr.open("POST", "receive.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonString);
这是我的php文件
<?php
header('Content-Type' , 'application/json');
$requestPayload = file_get_contents('php://input');
$json = json_decode($requestPayload , true);
$not = 'gsvcgdsqc';
//This gives NULL
var_dump($json);
echo $not;
?>
在浏览器(网络)中,我可以看到发送的数据:
但是当我尝试将它存储在一个变量中并显示它时,它给出了 null :
那么如何访问这些数据并将其存储在一个变量中,以便我可以将它们用于其他操作呢?
由于您使用的是 jQuery:
$.ajax({
type: 'POST',
url: 'receive.php',
data: data
});
然后您可以使用$_POST
获取数据,不需要 json。
当您在浏览器的地址栏中键入 URL 时,它显示为NULL
。
这是与您使用 JavaScript 发出的 POST 请求完全不同的 (GET) 请求。
POST 请求的请求体(包含 JSON)在 GET 请求中不存在,所以当然是 NULL。
如果您想查看对您发出的 POST 请求的响应,请查看“预览”选项卡而不是“网络”监视器中的“标题”选项卡。
如果您想将数据存储在某处,然后在随后的请求中将其读回,那么您需要通过编写代码来明确地做到这一点。
首先选择某个地方来存储它(例如会话或数据库)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.