Javascript 如何在Firefox28.0中发出正确的XHR POST请求?
在Firefox28.0中完成一个简单的XHR POST后,我的服务器php脚本POST数组为空。请求的来源相同 在触发请求的js脚本中,我有:Javascript 如何在Firefox28.0中发出正确的XHR POST请求?,javascript,http,firefox,post,xmlhttprequest,Javascript,Http,Firefox,Post,Xmlhttprequest,在Firefox28.0中完成一个简单的XHR POST后,我的服务器php脚本POST数组为空。请求的来源相同 在触发请求的js脚本中,我有: $(function(){ $("#head").click(function(){ var invocation=new XMLHttpRequest(); var url="test.php"; var body="hello"; if (invocation) { invocation.open("POST",url, true);
$(function(){
$("#head").click(function(){
var invocation=new XMLHttpRequest();
var url="test.php";
var body="hello";
if (invocation)
{
invocation.open("POST",url, true);
invocation.onreadystatechange=handler;
invocation.send(body);
}
function handler(evtXHR){
if(invocation.readyState===4)
{
if(invocation.status===200)
{
alert("success");
}
}
}
});
});
在我的php文件中,我有:
<?php
header('Access-Control-Allow-Origin: *');
$data=$_POST['body'];
var_dump($data);
?>
请求头:
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0
Referer: .......
Pragma: no-cache
Host: ..........
Content-Type: text/plain; charset=UTF-8
Content-Length: 5
Connection: keep-alive
Cache-Control: no-cache
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
请求正文:
你好
响应标题
X-Powered-By: PHP/5.2.17
Transfer-Encoding: chunked
Server: Apache
Keep-Alive: timeout=5, max=100
Date: Wed, 16 Apr 2014 19:04:55 GMT
Content-Type: text/html
Connection: Keep-Alive
access-control-allow-origin: *
请帮我弄清楚发生了什么。为什么请求成功后POST数组为空?
谢谢。您将请求正文编码为纯文本。PHP不会将其解析为
$\u POST
访问原始消息正文
file_get_contents('php://input')
或者以PHP可以理解的格式对请求中的数据进行编码
var data="hello";
var body = "someKeyName=" + encodeURIComponent(data);
// ...
invocation.open("POST",url, true);
invocation.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
invocation.send(body);
及
谢谢,我不知道怎么做。我将invocation.setRequestHeader(“内容类型”、“文本/html”);在我的js文件中,但这不起作用。我应该将纯文本编码成不同的mime类型吗?我按照你的建议做了所有事情,但POST数组仍然是空的。。这个问题可能是由其他原因引起的吗?我在var_dump($\u POST[“someKeyName”])上有NULL,但是HTTPfox插件显示字符串(5)“hello”,这表明var_dump()实际上说了些什么。因为当我在脚本中放入echo()而不是var_dump()时,HTTPfox只写“hello”,因为echo()函数将正常工作。听起来您仍然在发送
数据,而不是body
。不,不,我这样发送body:var body=“name=+encodeURIComponent(数据);然后调用。发送(body);在php脚本var_dump($_POST['name'])中;在我做了Quentin建议的更改后,我的php脚本中的var_dump$_POST仍然为null,然而,HTTPfox插件显示内容是字符串(5)“hello”whan is use var_dump and“hello”,当我在脚本中使用echo()时。如何解决这些问题?
var data="hello";
var body = "someKeyName=" + encodeURIComponent(data);
// ...
invocation.open("POST",url, true);
invocation.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
invocation.send(body);
$data=$_POST['someKeyName'];