2017-08-13 187 views
0

正如标题所述,我正在寻找使用JavaScript进行POST请求,并且得到响应。这里是我当前的代码:AJAX 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']; 
?> 

这应返回 '红',而是返回任何内容。

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

+0

**危险**:此代码[易受XSS影响](https://www.owasp.org/index.php/XSS)用户输入在插入HTML文档之前需要转义! – Quentin

+0

**警告**:可以通过查询字符串,发布数据或cookie填充'$ _REQUEST'。命名冲突(特别是涉及cookie时)可能会导致混淆。最好避免使用更明确的superglobals'$ _COOKIES','$ _POST'和'$ _GET'。 – Quentin

+0

是的,我知道这很容易受到XSS的影响 - 我很快把它放在一起,因为我不想上传我的真实代码。 – 073148974301870437087

回答

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'); 
+0

呵呵。我认为这会起作用,但它仍然没有给我什么。 – 073148974301870437087

+0

这使得请求内容类型为“text/plain”,因此PHP不知道如何对其进行解码,并且未填充“$ _REQUEST”。您可以手动设置Content-Type,但FormData是一种更好的方法。 – Quentin

+0

好点@Quentin〜测试过,发现没有反应...添加标题 - 繁荣! – RamRaider

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的问题

目前所有的解决方案的简单的“test.php的”源代码登录,而不是记录“红色”到控制台

控制台

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

+0

这只是记录我输入到控制台的源代码... – 073148974301870437087

+0

@ 073148974301870437087 - 当我测试它时,它完美运行:http://i.imgur.com/qFAdiU7.png – Quentin

+0

http://imgur.com/a/bLWpZ – 073148974301870437087