从json_encode返回[Object object]

时间:2016-10-04 19:06:08

标签: javascript php jquery json ajax

我无法将状态消息从php文件返回到html文件中的ajax函数。当提交时我在屏幕上得到[对象对象]。根据我的理解,json_encode可以返回对象$ answer及其值。我在这里错过了什么吗?

PHP

<?php  
 require_once 'dbconfig.php';
 require_once('FirePHPCore/fb.php');
 ob_start();

  $answer = new stdClass;
 if(isset($_POST))
 {
     $uname;
     $pword;
     //email = ema
     $ema;

     $answer->result = "successful";
     $answer->text = "";
     foreach($_POST as $key => $value)
     {
        if($key == 'u')
        {
            $uname = $value;
        }
        else if($key == 'p')
        {
            $pword = $value;
        } 
        else if($key == 'em')
        {
            $ema = $value;
        }
     }
    }
    else
    {
        $answer->result = "Error";
        $answer->text = "Error Message";
    }

    $check = mysqli_query($con, "SELECT username FROM users WHERE username = '$uname'")  or die(mysql_error());  
    $check2 = mysqli_num_rows($check);

    if ($check2 != 0) {  
    $answer->text = "sorry username taken";
    $ansr = json_encode($answer);
    echo $ansr;
    die('Sorry, the username is already in use.'); 
     }
   exit(0);
?>

我的html文件中的ajax

 $.ajax({
            type: "POST",
            url: "registration.php",
            dataType: "json",
            data : { u: un, p:p1, e:em },
            cache: !1,
            beforeSend: function(){
                $("#submit").hide();
                $('#status').text('please wait ...');
            },
            complete: function(){
                $("#submit").show();
            },
            success: function(answer){
                if(answer.result == "successful")
                {
                    $("#status").html(answer.text);
                }
                else
                {
                    $("#status").html(answer.result);
                }
            },
            error: function(answer){
                $("#status").text(answer);
            }
        });

任何建议或提示都将不胜感激。

1 个答案:

答案 0 :(得分:0)

谢谢@RamRaider! 使用json_encode后立即使用die()使数据无效。