如何在PHP中通过POST从xmlhttp.send(str)获取字符串

时间:2013-07-01 13:25:44

标签: php javascript ajax http

我的代码看起来像这样: 客户端JavaScript:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",url + page,true);
xmlhttp.send(str);

我在PHP方面缺少代码来提取这个字符串,我假设它在http帖子体中。

是否可以发送字符串数组,或者此方法是否受限于xmls和字符串?

2 个答案:

答案 0 :(得分:2)

您可以发送您喜欢的任何数据。

通常,您会将数据编码为 application / x-www-form-urlencoded

var data = "foo=" + encodeURIComponent(data) + "&bar=" + encodeURIComponent(more_data);
xmlhttp.send(data);

然后通过$_POST['foo']$_POST['bar']访问它。

如果您想访问原始数据,则可以通过file_get_contents('php://input');

访问该数据

使用setRequestHeader指定要发送的数据的内容类型。

答案 1 :(得分:0)

正如Canttouchit所说,必须为任何POST请求发送这些标头:

xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // for POST escaped 'form' data
xhttp.setRequestHeader("Content-length", post_str.length);
xhttp.setRequestHeader("Connection", "close");