JSON结果无法在PHP代码中与jQuery一起正常工作

JSON结果无法在PHP代码中与jQuery一起正常工作,php,jquery,ajax,json,Php,Jquery,Ajax,Json,我有一个由AJAX返回的JSON数据: PHP文件: //SQL: fetch result if user exist $result = array("Name"=>$name, "ID"=>$id, "Age"=>$age, "School"=>$school, "Department"=>$dept); echo json_encode($result); //else return error $error = 'No record

我有一个由AJAX返回的JSON数据:

PHP文件:

//SQL: fetch result if user exist
    $result = array("Name"=>$name, "ID"=>$id, "Age"=>$age, "School"=>$school, "Department"=>$dept);
    echo json_encode($result);
//else return error
    $error = 'No record for this user.';
    $result = array("Error"=>$error);
    echo json_encode($result);
//AJAX result
request.done(function( msg ):
//alert( msg ); working fine for users who exist and even those who doesn't exist.
var detail = jQuery.parseJSON( msg );
 if ( detail.Name.length > 0 ){
      $('.student').slideDown(300);
      $('.student').html(detail.Name);
      // this is working fine
    }
 if ( detail.Error.length > 0 ){
     $('.student').slideDown(300);
     $('.student').html(detail.Error); 
     //this is not working even if the user does not exist.
    }
jQuery AJAX:

//SQL: fetch result if user exist
    $result = array("Name"=>$name, "ID"=>$id, "Age"=>$age, "School"=>$school, "Department"=>$dept);
    echo json_encode($result);
//else return error
    $error = 'No record for this user.';
    $result = array("Error"=>$error);
    echo json_encode($result);
//AJAX result
request.done(function( msg ):
//alert( msg ); working fine for users who exist and even those who doesn't exist.
var detail = jQuery.parseJSON( msg );
 if ( detail.Name.length > 0 ){
      $('.student').slideDown(300);
      $('.student').html(detail.Name);
      // this is working fine
    }
 if ( detail.Error.length > 0 ){
     $('.student').slideDown(300);
     $('.student').html(detail.Error); 
     //this is not working even if the user does not exist.
    }

如何解决这个问题?

在检查detail.Name.length时,脚本编写将失败。该错误将停止Javascript执行其余部分

如果出现错误,您的JSON数据将如下所示:

   {"Error":"No record for this user."}
如果然后运行JavaScript代码:

if(detail.Name.length>0) 
。。。Javascript将返回“uncaughttypeerror:cannotreadproperty'length'of undefined…”,它将停止执行所有其他Javascript代码,因此它永远不会到达错误处理程序

要解决此问题,请在知道记录存在之前不要检查其长度:

if(typeof detail.Name!="undefined" && detail.Name.length>0){
   ... etc... 

在本例中,您甚至不必检查长度,如果设置了“name”,您就知道它是由PHP脚本设置的

什么是
console.log(细节)如果你在
错误
段中调用它,它会给你什么?@Khôi:
回音
只有一次。它会根据满足的条件进行一次回音:是否有学生在DB中找到。@hjpotter92:它显示
[对象对象]
。使用chrome和console.log(详细信息)可以查看对象及其属性。你是说
console.dir()
?或者,
详细信息是“错误”
详细信息是“名称”