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条)

报告相同问题?

悬赏问题

  • ¥20 云卓h12pro 数传问题
  • ¥20 请问有人知道怎么用工艺库里面的sdb文件通过virtuoso导出来library里面每个cell的symbol吗?
  • ¥20 海思 nnie 编译 报错
  • ¥50 决策面并仿真,要求有仿真结果图
  • ¥15 springboot接入微信支付SDK
  • ¥50 大区域的遥感影像匹配 怎么做啊
  • ¥15 求解答:pytorch跑yolov8神经网络受挫
  • ¥20 Js代码报错问题不知道怎么解决
  • ¥15 gojs 点击按钮node的position位置进行改变,再次点击回到原来的位置
  • ¥20 halcon 图像拼接