php - 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 操作。非常感谢大家。
编辑:
- post_max_size 到我的 php.ini 是 16M
- 只有当我将 POST 方法放入 ajax 时,file_get_contents("php://input") 才会返回空白
- var_dump($_POST) 返回数组 (0) {}
- var_dump($_SERVER['REQUEST_METHOD']) 返回 string(3) "GET" 但我不知道为什么,因为我已经设置为 ajax POST 和 php 代码请求方法 == POST
- 更新了 ajax 调用,但仍然无法正常工作
有没有非常擅长这些事情的人可以帮助我?可能问题出在 htaccess 中,但我不知道如何更改它
解决方案
你说:
contentType: false,
processData: false,
这让底层XMLHttpRequest
对象解释您传递的数据,将其转换为 HTTP 格式标准并Content-Type
在请求中设置正确的标头。
当您将对象传递给它时,这很棒。FormData
你不是。
你传递给它一个普通的对象。因此它将其转换为字符串 ( "[object Object]"
) 并设置默认Content-Type: text/plain
IIRC)。
PHP 不知道如何处理这种类型的数据,而且真正的数据已经丢失了。
不要设置这两个指令。jQuery 将处理普通对象,格式化数据并Content-Type
为您设置。
推荐阅读
- javascript - 如果正则表达式匹配连续的分隔符,则添加空字符串
- python - 如何通过程序获取 chrome 配置文件路径?
- python - 为什么 selenium 无法在我的 mac 上安装它?
- node.js - 无法访问 npm
- javascript - Twilio 可编程视频 - 加入房间时出现 Web Socket 错误
- airflow - Airflow BigQueryOperator:如何将输出数据保存到指定的分区列而不是摄取时间
- spring-boot - 当我发送 JSESSIONID 时,Spring Boot 基本身份验证忽略了授权标头?
- php - docker 容器中未指定应用程序加密密钥
- android - Android Jetpack:如何使用 PagingDataAdapter 在回收器视图中进行多选?
- azure - 使用 dot net 进行 Azure 批处理作业调度