2013-05-09 237 views
0

我試圖讓AJAX調用,這是我第一次使用AJAX,我的代碼如下:AJAX GET請求不工作

$.get("validate.php", { 'userinput':'x'}, function(response) { 
    if(response.status) alert("Matches found"); 
    else alert("No matches"); 
}); 

vaidate.php:

<?php 
$user_input=$_GET['userinput']; 
//print_r($user_input); 
if(!is_null($user_input)) exit('{ "status": true }'); 
else exit('{ "status": false }'); 
?> 

如果我訪問我的validate.php,我得到「未定義索引」錯誤。什麼是正確的方法來做到這一點?

+1

好,一,'的print_r($ USER_INPUT);'需要的jQuery被註釋掉正確解析回報,但首先需要解決未定義指數誤差 – 2013-05-09 18:09:49

+0

語法是有點過 - 你不需要最後的'}' – karthikr 2013-05-09 18:10:54

+0

是的,它在代碼中被評論了,對不起。那是隻有當我測試出來 – 2013-05-09 18:11:34

回答

1

PHP的,一旦你註釋掉測試代碼看起來不錯:

<?php 
    $user_input=$_GET['userinput']; 
    //print_r($user_input); 
    if(!is_null($user_input)) exit('{ "status": true }'); 
    else exit('{ "status": false }'); 
?> 

你需要指定你期望JSON,最簡單的方法是使用的getJSON

$.getJSON("validate.php", { 'userinput':'x'}, function(response) { 
    if(response.status) alert("Matches found"); 
    else alert("No matches"); 
}); 

其他替代用jQuery是

$.get("validate.php", { 'userinput':'x'}, function(response) { 
    if(response.status) alert("Matches found"); 
    else alert("No matches"); 
},"json"); 

,或者設置在PHP ContentType標頭:

<?php 
    $user_input=$_GET['userinput']; 
    //print_r($user_input); 
    header('Content-type: application/json'); 
    if(!is_null($user_input)) exit('{ "status": true }'); 
    else exit('{ "status": false }'); 
?> 
+1

其他選項是將「json」作爲第四個參數傳遞給'$ .get()',或將響應的Content-Type設置爲「application/json」。雖然我同意這是最好的設置 – Ian 2013-05-09 18:17:56

+0

非常感謝,它的工作原理! – 2013-05-09 18:19:31

+0

erm ....'jQuery.ajax()'是最好的設置:P – itachi 2013-05-09 18:21:45