Javascript 从带有参数的 XMLHttp POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7071544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:43:37 来源:igfitidea点击:
POST from XMLHttp with parameters
提问by styfle
I'm trying to post data to a PHP page and check the response. Here is an example. What is wrong with this code?
我正在尝试将数据发布到 PHP 页面并检查响应。这是一个例子。这段代码有什么问题?
index.html
索引.html
<html>
<head>
<title>Post Ajax</title>
<script type="text/javascript">
function post(foo, bar) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "ajax.php", true);
xmlhttp.send("foo=" + foo + "&bar=" + bar);
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="post('one','two');" />
</body>
</html>
ajax.php
ajax.php
<?php
if (array_key_exists('foo', $_POST) && array_key_exists('bar', $_POST)) {
$foo = $_POST['foo'];
$bar = ($_POST['bar']);
// do stuff with params
echo 'Yes, it works!';
} else {
echo 'Invalid parameters!';
}
?>
Either I have a stupid typo or I am not using the send() method correctly.
要么我有一个愚蠢的错字,要么我没有正确使用 send() 方法。