AJAX,好吧,POST不行

Jue*_*gen 5 php ajax jquery debian

Ajax GET请求正常工作.但我必须使用POST,因为我希望发送更多的数据,对GET来说太多了.

环境:Apache 2,Debian 9(从头开始),jQuery 3.2.1,没什么特别的.

我把问题解决了这段代码:

客户

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="de">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Ajaxtest</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <script language="JavaScript">
    <!--
    $.ajax({
        url: 'ajaxtest2.php',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        data: {testdata: 'here I am'},
        success: function (resp) {
            console.log(resp);
        },
    });
    -->
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

服务器

<?php
ini_set('error_reporting', E_ERROR);
header('Content-type: application/json'); 
header('HTTP/1.1 200 OK');
print json_encode(
    array(
        'method'=>$_SERVER['REQUEST_METHOD'],
        'get'=>$_GET['testdata'],
        'post'=>$_POST['testdata'])
    );
exit();
?>
Run Code Online (Sandbox Code Playgroud)

当通过GET发送ajax调用时我只会改变

type: 'POST'
Run Code Online (Sandbox Code Playgroud)

type: 'GET'
Run Code Online (Sandbox Code Playgroud)

这给了我在控制台上的这个结果:

{方法:"获取",获取:"我在这里",发布:null}

这是你所期望的.

但是当通过POST调用时,我得到:

{方法:"POST",get:null,post:null}

服务器了解POST请求但不提供任何值.

我尝试了不同的方法,包括目标网址,有些人建议使用相同的结果

url: 'ajaxtest2.php'
url: './ajaxtest2.php'
url: './ajaxtest2.php/'
Run Code Online (Sandbox Code Playgroud)

它们都没有区别:$ _POST保持空白.

此外,我在服务器上记录了get_defined_vars(),但$ _POST保持为空,并且在转储变量中没有任何"我在这里"的痕迹.

没有.htaccess混合网址重写等.

我还可以做些什么?

Inc*_*Hat 1

我的评论有效的长答案是:

您尝试使用以下内容类型将数据发送到服务器:

application/json; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

而不是发送 POST 数据的默认和规范:

application/x-www-form-urlencoded; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)

在服务器端,它没有将 contentType 作为表单帖子,而是作为application/json. 这意味着没有数据放入 $_POST 变量中供 php 使用。

GET 则不同,因为数据位于 URL 中,而不是正文中。

对于 ajax 调用,编码类型应始终为 utf-8,因此这也不是问题。

您通常不应该将 json 数据发送到这样的服务器。仅当您将数据发送到需要在接受时解析的原始 json 数据的应用程序时,它才适用。对于 PHP 服务器,它需要“表单数据”(否则您需要阅读php://input,请参阅下面的底部参考网址)。

希望有助于消除困惑。

更多信息: http://api.jquery.com/jquery.ajax/(contentType信息) https://forum.jquery.com/topic/ajax-with-contenttype-application-json(最后一篇文章很有帮助)