带响应的AJAX POST请求

时间:2017-08-13 18:42:25

标签: javascript php ajax

正如标题所述,我正在寻求使用JavaScript发出POST请求并获得响应。这是我目前的代码:

var request = new XMLHttpRequest();
request.open('POST', 'test.php', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success
    console.log(request.responseText)
  } else {
    // Server-side Error
    console.log("Server-side Error")
  }
};

request.onerror = function() {
    // Connection Error
    console.log("Connection Error")
};

request.send({
    'color':'red', 
    'food': 'carrot',
    'animal': 'crow'
});

test.php为:

<?php 
    echo $_POST['color'];
?>

这应该返回'red'但不返回任何内容。

这似乎是一个简单的问题,但我只能找到使用jQuery的人的解决方案。我想要一个不依赖的解决方案和库。

2 个答案:

答案 0 :(得分:0)

send方法采用字符串而不是对象,可能更像是:

var request = new XMLHttpRequest();
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    console.log(request.response)
  } else {
    console.log("Server-side Error")
  }
};

request.onerror = function() {
    console.log("Connection Error")
};

request.open('POST', 'test.php', true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.send('color=red&food=carrot&animal=crow');

答案 1 :(得分:0)

JavaScript问题

您正在尝试发送通用对象,因此它会转换为字符串("[Object object]"),并且数据会丢失。

转而将数据转换为FormData对象。

var data = {
    'color':'red', 
    'food': 'carrot',
    'animal': 'crow'
};

var formData = new FormData();

Object.keys(data).forEach(function (key) { 
  formData.append(key, data[key]);
})

request.send(formData);

PHP问题

  

所有当前解决方案只需记录&#34; test.php&#34;的源代码。到了控制台,而不是记录红色&#39;到控制台

这是与您的代码无关的问题。它也是一个FAQ。请参阅:PHP code is not being executed, instead code shows on the page

相关问题