【问题标题】:I am not able to send a string correctly from javascript to server我无法将字符串从 javascript 正确发送到服务器
【发布时间】:2018-12-18 14:20:26
【问题描述】:

我正在尝试使用以下脚本向我的服务器发送一个字符串:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.send(data);

但是,在服务器端,当 execute.php 被执行时,

isset($_POST['name']) 

它返回false。这是对服务器的唯一请求。

为什么没有设置$_POST['name'] 以及如何解决它?

【问题讨论】:

  • HMLHttpRequest 是这里的拼写错误,还是您有这样的错误?不应该是XMLHttpRequest吗?
  • 是的,对不起,我在原始代码中正确使用了它。
  • 我认为您缺少请求标头...尝试:xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); (在您发送数据之前)

标签: javascript php post xmlhttprequest


【解决方案1】:

在发送数据之前尝试设置请求头:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);

【讨论】:

  • 内容类型的好消息
  • 这件事发生在我身上太多次了,它可能会触发 $_POST 变量的错误值。
  • 成功了,谢谢!但它是否可能不适用于像 base64 图像这样的长字符串?它是否受到某种限制?
  • @EricValls 不用担心,您可以在 php.ini 文件中限制 php_value post_max_size。我在我的一台服务器中使用了 512M 的值,效果很好。
【解决方案2】:

在 POST(MIME 类型)时,有多种方法可以对数据进行编码。 PHP 的 $_POST 只会自动解码 www-form-urlencoded

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var data = 'name=John';   

xhr.send(data);

如果你发送 JSON 编码的数据,你必须阅读整个帖子正文并自己进行 json 解码。

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
var data = JSON.stringify({'name':'John'});

xhr.send(data);

在 PHP 中...

$entityBody = file_get_contents('php://input');
$myPost = json_decode($entityBody);
$myPost['name'] == 'John';

使用浏览器的网络检查器 (f12) 查看发生了什么。

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多