简体   繁体   中英

How to correctly receive data sent by AJAX

I have this XMLHttpRequest library:

 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:

 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:

<?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? (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'.

So instead of:

json_encode($_POST)

you can use:

file_get_contents('php://input')

Note that the result is still in JSON format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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