AJAX GET请求无效

时间:2013-05-09 18:07:58

标签: php javascript jquery ajax get

我正在尝试进行AJAX调用,这是我第一次使用AJAX,我的代码如下:

$.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 个答案:

答案 0 :(得分: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 }' );
?>