2013-05-09 243 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