【问题标题】:Send a HTTP Request w/ JavaScript使用 JavaScript 发送 HTTP 请求
【发布时间】:2014-12-24 16:25:57
【问题描述】:

所以我有一个这样的 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

【问题讨论】:

  • 你不是在做$_GET吗?
  • 这个字符串肯定是$_GET字符串:pages/page.php?cv=1。

标签: javascript php ajax http xmlhttprequest


【解决方案1】:

如果你要使用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");
    }
}

【讨论】:

    【解决方案2】:

    你可以这样:

     $cv =  isset($_POST['cv']) ? $_POST['cv'] : '';
    

    希望能帮到你!

    【讨论】:

    • 这会停止错误,但在这种情况下,变量没有设置,所以我无法访问它。
    • 你不必给你的方法传参数,方法不是可变参数。
    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 2018-02-07
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多