使用 php 从 ajax 检索发布的数据

Retrieving posted data from ajax using php

我在从 ajax 调用中检索 posted 数据时遇到问题,不确定哪里出了问题。以下脚本的控制台输出显示 ajax 调用之前的所有内容,但数据在连接器

中不可用
   function updateOptions(data){

        console.log(data);
        console.log(data.id);
        console.log(data.action);

        var data = {id: data.id, action : data.action};

        console.log(data);

        $.ajax({

            type: 'POST',
            url: 'ajax.connector.php?action=updateOptions',
            data: JSON.stringify(data),
            cache: false,
            dataType  : "json",

            success: function(data, status) {

                if(data.status == 'success'){

                console.log('success');
                console.log(data);

                }else if(data.status == 'error'){
                    console.log('selects not updated');
                }

            },

            error: function(data){
                console.log('an error has occurred');
            },

        });

    }

因此前 4 个 console.log 条目正确显示数据,成功条件中的第一个 console.log 正确显示。第二个,显示:

Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}

连接器[更像导演]

   case 'updateOptions':
        error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
        $output = $sbb->updateOptions($_POST);
        break;

记录这个:

Running updateOptions function Array\n(\n)\n,

如果我尝试将 $_POST['action'] 或 $_POST['data'] 或其他内容回显到日志中,我会得到一个未定义的索引。

我在 php 案例函数正在调用的 class 中强制 ajax 调用 return 成功:

public function updateOptions($data){

        $output = array(
            'status' => 'success',
            'msg' => 'Category added successfully',
            'id' => $data['id'],
            'action' => $data['action'],
            'post' => $data,
        );

        return $output;

}

所以 ajax 调用本身确实有效,它是未传递的数据。

不知何故,我没有从 ajax post.

获取 [或正确检索] 数据

这里有什么问题?

您正在发布 JSON,$_POST 由键=值对填充,请勿将 JSON 与 application/x-www-form-urlencodedmultipart/form-data(这是php 用来填充 $_POST.
的内容 要使用 jQuery.ajax 发送 application/x-www-form-urlencoded 数据,请将数据作为数据参数传递一个对象

data: data, // removed JSON.stringify