【问题标题】:In php, how do I get the text/plain value of send() method of XMLHttpRequest在 php 中,如何获取 XMLHttpRequest 的 send() 方法的文本/纯文本值
【发布时间】:2011-11-15 19:55:35
【问题描述】:

我不知道如何获得“Hello World!”在 PHP 中用于以下 Javascript 代码。
我知道如果内容类型是“application/x-www-form-urlencoded”,我可以使用 $_POST[''],但不能使用“text/plain”。

var xhr = new XMLHttpRequest();
xhr.open('POST', 'example.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('Hello World!');

【问题讨论】:

    标签: php javascript ajax xmlhttprequest


    【解决方案1】:

    此 PHP 将从请求正文中读取原始数据:

    $data = file_get_contents('php://input');
    

    第 3 行:

    xhr.setRequestHeader('Content-Type', 'text/plain');
    

    不需要,因为发布纯文本会将内容类型设置为 text/plain;charset=UTF-8
    http://www.w3.org/TR/XMLHttpRequest/#the-send-method

    【讨论】:

    • 虽然我同意“正确”的标准做法是始终正确格式化表单数据,但“php://input”位是一个值得注意的有趣细节。更多信息可以通过网络搜索找到:link
    • 以纯文本形式发送 POST 数据的问题在哪里?我从未读过 HTTP 标准要求 POST 数据为“application/x-www-form-urlencoded”,例如 PHP 和浏览器使用它来进行比 HTTP 高一级的通信
    【解决方案2】:

    您的请求存在许多问题。如果不使用application/x-www-form-urlencoded,您将无法发布数据。其次,“Hello World!”没有转义或附加到变量。

    以下是 POST 数据到服务器的 javascript 代码。

    var xhr = new XMLHttpRequest();
    var params = 'x='+encodeURIComponent("Hello World!");
    xhr.open("POST", 'example.php', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    xhr.send(params);
    

    您可以在 PHP 中使用$_POST['x'] 访问它。

    或者,您可以通过以下代码使用$_GET['x']

    var xhr = new XMLHttpRequest();
    var params = encodeURIComponent("Hello World!");
    xhr.open("GET", 'example.php?x='+params, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    xhr.send(null);
    

    GET更符合使用Content-type: text/plain的思路。

    【讨论】:

    • 这就是我想知道的全部内容 :) 谢谢
    • @genkidesu:我知道你是新来的。本网站习惯于接受您认为有帮助的答案。否则,人们将更不愿意回答您以后可能遇到的任何问题。
    • @abc 您应该将 Herbert 回复标记为已接受。您好 Herbert,感谢您的正确陈述,我在 w3school 上的尝试没有成功,与您相比,他们的陈述看起来混乱且不完整(我想知道它是如何工作的)
    【解决方案3】:

    你可以试试http_get_request_body (http://php.net/manual/en/function.http-get-request-body.php)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多