读取通过Ajax调用发送的PHP中的json数据

Read json data in PHP sent with an Ajax call

本文关键字:PHP 中的 json 数据 Ajax 调用 读取      更新时间:2024-01-24

开发的前端通过Ajax调用发送一个格式化为JSON对象的数据数组。json对象如下所示:

{
 "name": " Test Name ",
 "image_url": "test URL",
 "include": [
  "1"
 ],
 "dimension": [
  null
 ],
 "media_type": [
  null
 ],
 "match": [
  "1"
 ],
 "content": [
  "test content"
 ],
 "sorting": {
  "rating": "50",
  "language": "50",
  "CS Weight": "50",
 }
}

如何在我的PHP控制器中读取它。我可以这样拿吗:

$data = $_POST;

因为在这种情况下包含JSON对象的变量没有名称,所以我无法通过这种方式获取

$data = $_POST['data']

编辑部分


从前端,数据以这种方式发送:

 sendAjax: function(value, url, callback){
            xhr = $.ajax({
                type: 'POST',
                url: url,
                data: value
            }).done(function(message){
                callback(message);
            }).fail(function(jqXHR, textStatus){
                console.log('failed to submit form, error type: '+textStatus);
            });
        }

从脚本的输入中读取它,在这里可以获得"原始"POST数据:

$json = file_get_contents('php://input');
$data = json_decode($json);

假设您在前端使用jquery,这应该可以工作。只需将其粘贴到您的javascript控制台中并运行即可(确保用您的网址替换路径。参数应该正确通过。

data = {
 "name": " Test Name ",
 "image_url": "test URL",
 "include": [
  "1"
 ],
 "dimension": [
  null
 ],
 "media_type": [
  null
 ],
 "match": [
  "1"
 ],
 "content": [
  "test content"
 ],
 "sorting": {
  "rating": "50",
  "language": "50",
  "CS Weight": "50",
 }
}
$.ajax({url:'/YOUR/PATH/HERE', data: {data: data}, type: 'post', dataType: 'json'})

发帖后我突然想到,你是在问收到JSON后如何解析,还是如何将其显示在$_POST哈希中?