In php, how do I get the text / equal value of the send () XMLHttpRequest method

I have no idea how to get "Hello World!" in PHP for the following Javascript codes.
I know that I can use $ _POST [''] if the content type was "application / x-www-form-urlencoded", but not for "text / plain".

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

This PHP will read the source data from the request body:

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

Line 3:

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

not required, since publishing plain text will set the content type to text / plain; charset = utf-8
http://www.w3.org/TR/XMLHttpRequest/#the-send-method

+7
source

There are several errors in your request. You can use tSTST data without using application/x-www-form-urlencoded . Secondly, "Hello World!" not escaped or bound to a variable.

Below is the javascript code for the POST data to the server.

 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); 

You can access this with $_POST['x'] in PHP.

Alternatively, you use $_GET['x'] using the following code.

 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 is more in line with the idea of ​​using Content-type: text/plain .

+4
source
0
source

All Articles