简体   繁体   English

如何正确接收AJAX发送的数据

[英]How to correctly receive data sent by AJAX

I have this XMLHttpRequest library: 我有这个XMLHttpRequest库:

 function easyHTTP() { this.http = new XMLHttpRequest(); } // Make an HTTP POST Request easyHTTP.prototype.post = function(url, data, callback) { this.http.open('POST', url, true); this.http.setRequestHeader('Content-type', 'application/json'); let self = this; this.http.onload = function () { callback(null, self.http.responseText); } this.http.send(JSON.stringify(data)); } 

At my HTML I have a button tag with id="btn" , I want to send some data to a PHP file (named "ajax.php") when I click this button, so I have: 在我的HTML上,我有一个带有id="btn"的按钮标记,单击此按钮时,我想将一些数据发送到一个PHP文件(名为“ ajax.php”),因此,我有:

 document.addEventListener("DOMContentLoaded", function() { const http = new easyHTTP(); // Create Data const data = { title: 'Custom Posts', body: 'This is a custom post1' }; document.getElementById('btn').addEventListener('click', function(e){ // Create Post http.post('ajax.php', data, function(err, response){ if(err) { alert(err); } else { alert(response); } }); e.preventDefault(); }); }); 

And at my "ajax.php" I have: 在我的“ ajax.php”中,我有:

<?php 

if($_SERVER['REQUEST_METHOD'] == "POST") {

  echo var_dump(json_encode($_POST));

}

?>

But all I get from return is an empty array, it should not come as the response the data that I sent? 但是我从return中得到的只是一个空数组,它不应该作为响应发送给我吗? (Const data with "title" and "body")? (用“标题”和“正文”构造数据)? What I'm doing wrong? 我做错了什么?

It seems that XMLHttpRequest doesn't send the body to $_POST but rather to 'php://input'. 似乎XMLHttpRequest不会将正文发送到$ _POST而是发送到'php:// input'。

So instead of: 所以代替:

json_encode($_POST)

you can use: 您可以使用:

file_get_contents('php://input')

Note that the result is still in JSON format. 请注意,结果仍为JSON格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM