【问题标题】:how to get string from xmlhttp.send(str) via POST in PHP如何通过 PHP 中的 POST 从 xmlhttp.send(str) 获取字符串
【发布时间】:2013-07-01 13:25:43
【问题描述】:

我的代码如下所示: 客户端 JavaScript:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",url + page,true);
xmlhttp.send(str);

我缺少在 PHP 端提取此字符串的代码,我假设它位于 http 帖子正文中。

是否可以发送字符串数组或者此方法仅限于 xmls 和字符串?

【问题讨论】:

    标签: php javascript ajax http


    【解决方案1】:

    您可以发送任何您喜欢的数据。

    通常,您会将数据编码为 application/x-www-form-urlencoded

    var data = "foo=" + encodeURIComponent(data) + "&bar=" + encodeURIComponent(more_data);
    xmlhttp.send(data);
    

    然后通过$_POST['foo']$_POST['bar'] 访问它。

    如果你想访问原始数据,那么你可以通过file_get_contents('php://input');访问它

    使用setRequestHeader 指定您要发送的数据的内容类型。

    【讨论】:

    • 我错过了什么吗?我正在构建它 var str = "user=" + encodeURIComponent(document.getElementById("user").innerText) + "&pwd=" + encodeURIComponent(document.getElementById("passowrd").innerText);我注意到了
    • 如果您在发送之前警告字符串会发生什么?您的浏览器的“网络”选项卡显示正在发送到服务器的内容是什么?您如何尝试在服务器上读取它? JS 控制台中是否出现任何错误消息?
    • 我设法提醒错误是密码 ID,但我只看到 user=&pwd
    • 是的,innerText 会给你<input> this content if it was valid, which it isn't </input>。你想要的价值。
    • 嗯,我认为重要的是要说您需要将以下内容添加到标题中,否则它将无法正常工作。 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    【解决方案2】:

    正如 Canttouchit 所说,必须为任何 POST 请求发送这些标头:

    xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // for POST escaped 'form' data
    xhttp.setRequestHeader("Content-length", post_str.length);
    xhttp.setRequestHeader("Connection", "close");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2011-01-25
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      相关资源
      最近更新 更多