donglu5612 2015-05-07 08:47
浏览 442
已采纳

Json对象从PHP返回json_encode(),但在我的javascript中无效的json对象

I echo a simple associative array read from a mySQL table back to my jquery b.m.o the json_encode($array) method. However, my .ajax call fails back in the jquery and it seems due to the object not being a valid json object. I did some debugging in chrome and under the network tab verified the response preview- does indeed look to be in perfect json format:

{"UserName":"DehanL","UserPassword":"admin","UserEmail":"dehan@rocketmail.com"}

Here is my php:

<html>
<body>

<?php



$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";

$inUsername = $_POST["name"];
$inPassword = $_POST["password"];


// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");


$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";

$result = mysqli_query($conn,$sql);

// Fetch one row
$row=mysqli_fetch_assoc($result);

//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword'])) 
    { 

    //$_SESSION['UserName'] = $row['UserPassword']; 
    //echo $_SESSION; 

    echo json_encode($row);

    } 

else { echo "Be gone imposter!"; }


$conn->close();


?>

</body>
</html>

Then the jquery:

$.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: 'php/loginrequest.php', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json' // what type of data do we expect back from the server

    })
    // using the done promise callback
    .done(function (data) {
        console.log("ajax done callback");
    })
    .fail(function (data) {
        console.log(data, "ajax failed callback");

        var IS_JSON = true;
        try {
            var json = $.parseJSON(data);
        } catch (err) {
            IS_JSON = false;
        }
        console.log(IS_JSON);
    });
  • 写回答

4条回答

  • duan0714 2015-05-07 09:28
    关注

    Your PHP starts like this:

    <html>
    <body>
    

    Whatever else it outputs after that, it isn't going to be valid JSON.

    I did some debugging in chrome and under the network tab verified the response preview

    Look at the raw preview. You seem to be looking at the rendered HTML preview.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。