php – 带有参数的XMLHttp POST
发布时间:2020-12-13 18:11:00 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试将数据发布到 PHP页面并检查响应.这是一个例子.这段代码有什么问题? 的index.html htmlhead titlePost Ajax/title script type="text/javascript" function post(foo,bar) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = f
我正在尝试将数据发布到
PHP页面并检查响应.这是一个例子.这段代码有什么问题?
的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 <?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()方法.
我想到了.我需要设置请求标头.
xmlhttp.open("POST",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send("foo=" + foo + "&bar=" + bar); source1 source2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |