[英]Send a HTTP Request w/ JavaScript
So I have a JavaScript function like this, 所以我有一个JavaScript函数,
var ajax = function(data, url, method, onfinish){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
onfinish(xmlhttp.responseText);
}
};
xmlhttp.open(method, "pages/page.php?cv=1", true);
xmlhttp.send("cv=1");
};
and I have a null link that should run the function, 我有一个应该运行该功能的空链接,
<a href="javascript:void(0)" onclick="ajax('cv=1', 'pages/page.php', 'POST', set)" class="link">Posts</a>
And here is my php file, 这是我的php文件,
<?php
$cv = $_POST["cv"];
if ($cv == "p1") {
include("posts.php");
} else if ($cv == "p2") {
include("users.php");
} else if ($cv == "p3") {
include("write.php");
} else if ($cv == "p4") {
include("signup.php");
}
?>
But I keep getting this error, 但我不断收到这个错误,
Notice: Undefined index: cv in /home/cabox/workspace/pages/page.php on line 2 注意:未定义的索引:第2行/home/cabox/workspace/pages/page.php中的cv
You can like this: 您可以这样:
$cv = isset($_POST['cv']) ? $_POST['cv'] : '';
I Hope can help you! 希望能对您有所帮助!
If you are going to use POST
you need to add: 如果要使用
POST
,则需要添加:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
So your function will be: 因此,您的功能将是:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.send(data);
Then in PHP: 然后在PHP中:
if(isset($_POST['cv'])) {
$cv = $_POST["cv"];
if ($cv == "1") {
include("posts.php");
} else if ($cv == "2") {
include("users.php");
} else if ($cv == "3") {
include("write.php");
} else if ($cv == "4") {
include("signup.php");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.