首页 > 解决方案 > php 文件的 $_POST 不起作用,但 $_GET 是的。Ajax 调用它,返回 200 OK 但是 $_POST 到 php 文件是空的

问题描述

这是 AJAX 代码:(在这个简单的示例中,“newContent”是“尝试连接”)

$.ajax({
        type: "POST", //i have tried method: "POST" but still not working
        url: "change.php",
        data: {"edit": newContent},
        success: function(response){
            console.log(response);
        },
        error: function(){
            console.log("ERR");
        }
    });

此代码有效,它返回 OK 并显示响应(由于 php 代码为空)。如果我在网络上查看,“编辑”变量由 php 代码显示,但如果我在代码中查找任何 POST 变量,我找不到任何变量。另一方面,通过 GET 请求,我发现一切正常,一切正常。我的 PHP 代码:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file_contents = file_get_contents("example.php"); //Get content of file        
    
    $new = $_POST['edit']; //get post data
    $new = nl2br($new);

    //This change text into file and save it.
    $pageName = explode('/pagine/', $_SERVER['HTTP_REFERER']);
    $number = $pageName[1];
    $pageName = $pageName[1].".php";
    
    $file_contents = str_replace("TESTO QUI", $new, $file_contents);
    $file_contents = str_replace("988", $number, $file_contents);
    $file_contents = str_replace("Versione ITA:", '<h2 style="color:blue">Versione ITA:</h2>', $file_contents);
    $file_contents = str_replace("Versione ENG:", '<br/>
            <hr>
            <h2 style="color:blue">Versione ENG:</h2>', $file_contents);
    
    file_put_contents($pageName, $file_contents);
}
?>

问题是,如果我将 POST 更改为 GET,它工作得很好,但如果我更改为 POST,它就不再工作了。为什么?

有人能帮我吗?拜托,我应该向 php 发送一个很长的变量(超过 8000 个字符),我绝对需要这个 post 操作。非常感谢大家。

编辑:

有没有非常擅长这些事情的人可以帮助我?可能问题出在 htaccess 中,但我不知道如何更改它

标签: php

解决方案


你说:

    contentType: false,
    processData: false,

这让底层XMLHttpRequest对象解释您传递的数据,将其转换为 HTTP 格式标准并Content-Type在请求中设置正确的标头。

当您将对象传递给它时,这很棒。FormData

你不是。

你传递给它一个普通的对象。因此它将其转换为字符串 ( "[object Object]") 并设置默认Content-Type: text/plainIIRC)。

PHP 不知道如何处理这种类型的数据,而且真正的数据已经丢失了。

不要设置这两个指令。jQuery 将处理普通对象,格式化数据并Content-Type为您设置。


推荐阅读