使用JavaScript发送HTTP请求

使用JavaScript发送HTTP请求,javascript,php,ajax,http,xmlhttprequest,Javascript,Php,Ajax,Http,Xmlhttprequest,所以我有一个像这样的JavaScript函数 var ajax = function(data, url, method, onfinish){ var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { onfinis

所以我有一个像这样的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");
};
我有一个空链接可以运行这个函数

<a href="javascript:void(0)" onclick="ajax('cv=1', 'pages/page.php', 'POST', set)" class="link">Posts</a>
这是我的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");
}
?>
但我一直在犯这个错误

注意:未定义的索引:第2行/home/cabox/workspace/pages/page.php中的cv

 $cv =  isset($_POST['cv']) ? $_POST['cv'] : '';
我希望能帮助你

如果要使用POST,您需要添加:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
因此,您的功能将是:

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);
然后在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");
    }
}

你不是在做$\u-GET吗?这个字符串肯定是一个$\u-GET字符串:pages/page.php?cv=1。这会停止错误,但在这种情况下,变量没有设置,因此我无法访问它。你不必向方法传递参数,方法不是变量参数。