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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题