简体   繁体   中英

Send a HTTP Request w/ JavaScript

So I have a JavaScript function like this,

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
$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

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM