简体   繁体   中英

Using ajax to post data to local server, cant set request name

I've created an AJAX request to send to my PHP server:

var xml = new XMLHttpRequest();
xml.open("POST", "question.php", true);
xml.setRequestHeader('question','test');
xml.send();

In PHP, I'm trying to receive the AJAX data, but unfortunetly, it's not working.

$qst = $_POST['question'];
return $qst;

Am I doing something wrong with the AJAX request? How do I set the name of the POST variable correctly? I'm guessing that's the problem.

You have three problems that prevent your code from working.

You are putting the data in the wrong place

POST data is sent in the body of the HTTP request, not the headers.

This is most easily achieved with the FormData object . (You can also set the Content-Type request header and format the data manually, but FormData saves you from having to think about all of that).

 var data = new FormData();
 data.append("question", "test");

 var xml = new XMLHttpRequest();
 xml.open("POST", "question.php", true);
 xml.send(data);

You aren't looking at the response

Well. You might be looking at the response in the Network tab of the Developer Tools in your browser, but I'm guessing you are not.

 xml.addEventListener("load", examine_response);

 function examine_response() {
     alert(this.responseText);
 }

Your PHP isn't outputting anything

return is used to pass data from a function back to whatever called it.

It won't output anything back to the browser. You need echo or similar for that.

$qst = $_POST['question'];
print $qst;

Bonus problem: Security vulnerability!

Your code is vulnerable to XSS attacks. You must not echo user input back in an HTML document without escaping it.

Since you are trying to send plain text back, tell the browser it is a plain text document (PHP defaults to saying it is HTML):

header("Content-Type: text/plain");
$qst = $_POST['question'];
print $qst;

使用$ _POST数组,您不会访问http标头,因为您只是在XMLHttpRequest中设置标头,它将无法工作,您需要在XMLHttpRequest中设置http主体。

You need to send the data through the AJAX send function (HTTP body), not by setting the HTTP headers. Though, you do need to set the request header to show PHP that we're sending form data, which I've done below.

var xml = new XMLHttpRequest();
xml.open("POST", "question.php", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send("question=test");

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