PHP $ _POST为空,即使正在发送数据; file(“php:// input”)有价值

时间:2016-03-26 19:49:11

标签: php jquery ajax post

几天前一切都在运作,但突然间它不再有效了。我想我已经尝试了一切,但没有改变,所以作为最后的手段来到SO!

我已浏览this article并检查了我的php.ini文件,并将post_max_size设置为8M

来自JS的Ajax请求:

$.ajax({
    url: "getFromDB.php",
    type: "post",
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}, // Tried with and without
    data: { action: "getRouteList" },
    success: function(obj){
        alert("Yay!");
    }
});

myPage.php

// From this SO answer: http://stackoverflow.com/a/14794856/4669619
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

var_dump($rest_json);
var_dump($_POST);

getRouteList();                         // Works

if (isset($_POST["action"]) && !empty($_POST["action"])) {
    file_put_contents('function_result.txt', "Action: Set" . PHP_EOL . PHP_EOL, FILE_APPEND);
    $action = $_POST["action"];

    if ($action == "getRouteList") {
        getRouteList();                 // Doesn't work (b/c $_POST isn't set)
    }

} else {
    file_put_contents('function_result.txt', "Action: Not set!" . PHP_EOL . PHP_EOL, FILE_APPEND);
}

var_dump输出:

string(19) "action=getRouteList"    // $rest_json
NULL                                // $_POST // NULL b/c of '='?

function_result.txt输出

Action: Not set!

Firebug信息:

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您正在混合contentType方法

如果你想继续使用json,你需要对发送的数据进行字符串化并使php保持相同的

var json = JSON.stringify({ action: "getRouteList" });
$.ajax({
    url: "getFromDB.php",
    type: "post",
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}, // Tried with and without
    data: json,
    success: function(obj){
        alert("Yay!");
    }
});

或者以编码形式发送,然后删除内容类型的header,并删除php中的file_get_contents()json_decode(),并且$ _POST将像任何普通表单提交一样使用