gpt4 book ai didi

php - 我正在努力做,_POST 是空的

转载 作者:可可西里 更新时间:2023-11-01 00:42:27 24 4
gpt4 key购买 nike

我看了又看,但没有什么能完全触及这个问题。

我正在尝试通过 Chrome 中的 JavaScript* 发送 XMLHttpRequest。这是我的页面:

<!DOCTYPE html>
<html>
<head>
<title>ROAM</title>
<script>
function post_something() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', "post_test.php", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send("This is my text.");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<table>
<tr><td><input type="button" value="POST a thingy"
onclick="javascript:post_something()">
</input>
</td></tr>
</table>
</body>
</html>

这是我的 PHP:

<?php
print_r($_POST);
/>

这显示在控制台中:

Array
(
)

如果某个地方能告诉我 XMLHttpRequest.send 到底做了什么,它到底发送了什么,PHP 如何解析它,以及 PHP 期望什么,我可以自己解决这个愚蠢的事情。

*请理解我不想使用表单或 jQuery。我想直接使用 XMLHttpRequest 对象,直到我确切了解它的工作原理以及 PHP 如何接收和解析它。

最佳答案

您应该将您的Content-Type 声明为application/x-www-form-urlencoded 并以key1=value1&key2 的形式制作数据字符串=value2&key3=value3.

function post_something() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', "post_test.php", true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = "text=This is my text.&text2=This is my second text.";
xmlhttp.send(encodeURI(data));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
}

输出:

Array
(
    [text] => This is my text.
    [text2] => This is my second text.
)

关于php - 我正在努力做,_POST 是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com