2014-10-29 154 views
1

所以我有一個JavaScript函數像這樣,發送一個HTTP請求W/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"); 
} 
?> 

,但我不斷收到此錯誤,

注意:未定義指數:簡歷/home/cabox/workspace/pages/page.php第2行

+1

你不做一個'$ _GET'? – Rasclatt 2014-10-29 03:31:22

+0

這個字符串絕對是'$ _GET'字符串:'pages/page.php?cv = 1'。 – Rasclatt 2014-10-29 03:37:39

回答

0

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

可以是這樣的:

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

我希望能幫助你!

+0

停止錯誤,但在這種情況下,變量未設置,因此我無法訪問它。 – 2014-10-29 03:41:51

+0

您不必將參數傳遞給您的方法,該方法不是可變參數。 – xiaoming 2014-10-29 03:54:55