PHP 无法识别 ajax 发布的数据

PHP isn't recognizing data posted by ajax

本文关键字:数据 ajax 识别 PHP      更新时间:2023-09-26

我正在向我的PHP脚本发送ajax调用,如下所示:

function load(){
    var request = {};
    request['action'] = 'load';
    request['file'] = 'lorem_ipsum.txt';
    $.ajax({
        type: 'POST',
        url: cgi_file,
        data: JSON.stringify(request),
        processData: false,
        dataType: 'html',
        contentType: 'application/html',
        success:function(response){
            console.log("received " + response);
        }
    });
}

我的PHP脚本如下:

$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
    case 'load':
        $file = $_POST['filename'];
        echo file_get_contents($content_dir . $file);
        exit();
}

PHP 响应失败如下:

Notice: Undefined index: action in /var/www/river/api.php on line 5

这里有什么问题?

尝试放弃processData: falsecontentType: 'application/html',它应该可以工作

$.ajax({
    type: 'POST',
    url: cgi_file,
    data: request,
    dataType: 'html',
    success:function(response){
        console.log("received " + response);
    }
});

只需保持原样data

data: request,

你不需要把它串起来。

此外,您的 file 参数允许攻击者从您的文件系统读取任意文件。对其进行消毒。

这里有一些错误,首先contentType属性用于您发送到服务器的数据,其次 dataType 应设置为 text因为这是您从服务器接收的内容。如果你想接收$_POST数组中的数据,你的javascript应该看起来像这样,

$.ajax({
    type: 'POST',
    url: cgi_file,
    data: {
        action: "load",
        file: "lorem_ipsum.txt";
    },
    dataType: 'text',
    success:function(response){
        console.log("received " + response);
    }
});

Jquery 会将您的数据作为标准帖子发送到您的服务器端代码。