通过不带jQuery的AJAX从JavaScript到PHP的POST值 [英] POST value from JavaScript to PHP via AJAX without jQuery
问题描述
我正在尝试发送一个JavaScript变量,以供PHP在服务器端进行处理,然后回显结果.我的ajax请求结果为readyState == 4
和status == 200
,但是PHP一直在回显一个空数组/值.
I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4
and status == 200
yet PHP keeps echoing back an empty array/value.
我很确定这来自我的Ajax调用,该请求发送了一个空请求,但是我尝试的所有操作均不起作用,所以也许我在这里出错了.
I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.
JS(来自index.html
):
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP(来自test.php
):
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
我的最后一次尝试是用.send(encodeURI('name=' + valueToSend));
更改request.send(valueToSend);
,但是它只是使ajax调用将页面位置重定向到一个不存在的页面.
My last try was to change request.send(valueToSend);
with .send(encodeURI('name=' + valueToSend));
but it just made the ajax call redirect the page location to a non-existing one.
我在做什么错了?
推荐答案
您的代码中几乎没有错误,例如:
There are few things wrong in your code, such as:
- 即使通过定义的
send_ajax()
函数,您也没有在代码中的任何地方调用它. -
使用
POST
请求,您需要将HTTP标头setRequestHeader()
与请求一起发送,如下所示:
- Even through you defined
send_ajax()
function, you didn't call it anywhere in the code. With
POST
request you need to send an HTTP headersetRequestHeader()
along with the request, like this:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
test.php 页面中的
echo $_POST['name'];
无法使用,因为此处name
是 undefined .您的send()
方法调用应如下所示:
echo $_POST['name'];
in test.php page won't work because name
is undefined here. Your send()
method call should be like this:
request.send("name="+valueToSend);
因此完整的JavaScript代码如下:
So the complete JavaScript code would be like this:
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("name="+valueToSend);
}
}
send_ajax();
这篇关于通过不带jQuery的AJAX从JavaScript到PHP的POST值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!