从POST XMLHttp的使用参数 [英] POST from XMLHttp with parameters
本文介绍了从POST XMLHttp的使用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想数据发布到一个PHP页面,并检查响应。下面是一个例子。什么是不对的code?
I'm trying to post data to a PHP page and check the response. Here is an example. What is wrong with this code?
index.html的
index.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!';
}
?>
无论我有一个愚蠢的错字或者我不使用send()方法正确。
Either I have a stupid typo or I am not using the send() method correctly.
推荐答案
我想它了。我需要设置请求头。
I figured it out. I needed to set the request header.
xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("foo=" + foo + "&bar=" + bar);
<一个href="http://stackoverflow.com/questions/4003711/why-is-post-array-empty-in-php-after-an-a-request-with-post-data">source1
这篇关于从POST XMLHttp的使用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文