AJAX和PHP响应给出“ SyntaxError:JSON输入意外结束”

时间:2018-11-15 16:44:00

标签: javascript php json ajax

我正在使用AJAX调用验证脚本。返回$response时,我不断收到错误SyntaxError: Unexpected end of JSON input。如果我不返回正确格式化为JSON的数据,我不会感到惊讶,但是现在我已经在JSON解析器中运行了响应{ "loggedIn": false },它似乎是有效的。我在做什么错了?

ajaxexample.php               

<form method="post" name="login">
    <input type="text" name="username" > Email/Username: <br>
    <input type="password" name="password" > Password: <br>
    <input type="submit">
</form>

<div id="content"></div>
</body>
</html>

<script>

$(document).on( 'submit', $("#login"), function(event){

    event.preventDefault();

    var formData = '{"login":[ {'+
                        '"username":"'+$('input[name="username"]').val()+'",'+
                        '"password":"'+$('input[name="password"]').val()+'"'+
                   '}]}';
   var formData = JSON.parse(formData);

    // Using the core $.ajax() method
    $.ajax({

    // The URL for the request
    url: "users/validate.php",

    // The data to send (will be converted to a query string)
    data: formData,

    // Whether this is a POST or GET request
    type: "POST",

    // The type of data we expect back
    dataType : "json",
    })
      // Code to run if the request succeeds (is done);
      // The response is passed to the function
      .done(function( data ) {

         $( "<div class=\"content\">").html( JSON.stringify(data) ).appendTo( "body" );
      })
      // Code to run if the request fails; the raw request and
      // status codes are passed to the function
      .fail(function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr.responseText );
      })
      // Code to run regardless of success or failure;
      .always(function( xhr, status ) {

      });
});
</script>

validate.php

<?php require_once '../users/init.php';?>

<?php
    if(isset($_POST))
    {

        $username = $_POST['username'];
        $password = $_POST['password'];

        $validate = new Validate();
        $validation = $validate->check($_POST, array(
          'username' => array('display' => 'Username','required' => true),
          'password' => array('display' => 'Password', 'required' => true)));

        if ($validation->passed()) 
        {
            $user = new User();
            $login = $user->loginEmail($username, $password, $remember);
            $response = array('loggedIn'=>$login);
            echo json_encode($response, JSON_PRETTY_PRINT );
        }
    }
    else
    {
        echo json_encode("No data.");
    }
?>

3 个答案:

答案 0 :(得分:2)

我在那里看到了几个问题

首先,要发送的数据格式错误,并且只需首先创建对象,就无需创建json字符串然后将其解析为对象。

var formData = {
                 "username": $('input[name="username"]').val(), 
                 "password": $('input[name="password"]').val()
               };

其次,由于您的数据格式错误,$validation->passed()将为假,并且您将在请求中不返回任何数据,这将要求使用json并在未得到时给出错误信息任何。

    if ($validation->passed()) 
    {
        $user = new User();
        $login = $user->loginEmail($username, $password, $remember);
        $response = array('loggedIn'=>$login);
        echo json_encode($response, JSON_PRETTY_PRINT );
    }
    else{
      echo json_encode(array('loggedIn'=>false), JSON_PRETTY_PRINT );
    }

此外,表单提交处理程序的选择器是错误的,应该类似于

$(document).on( 'submit', "[name=login]", function(event){

答案 1 :(得分:0)

您可能希望在php标记内的脚本顶部发送内容类型标头

header('content-type: application/json');

您可能会输出多余的字符,您可以尝试像这样输出缓冲区:

<?php

ob_start();
if(isset($_POST))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    $validate = new Validate();
    $validation = $validate->check($_POST, array(
      'username' => array('display' => 'Username','required' => true),
      'password' => array('display' => 'Password', 'required' => true)));

    if ($validation->passed()) 
    {
        $user = new User();
        $login = $user->loginEmail($username, $password, $remember);
        $response = array('loggedIn'=>$login);
        ob_clean();
        echo json_encode($response, JSON_PRETTY_PRINT );
        ob_flush();
    }
}
else
{
    ob_clean();
    echo json_encode("No data.");
    ob_flush();
}

答案 2 :(得分:-1)

validate.php不需要JSON对象,而只是在POST中形成数据。

<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<form method="post" name="login">
    <input type="text" name="username" > Email/Username: <br>
    <input type="password" name="password" > Password: <br>
    <input type="submit">
</form>

<div id="content"></div>
</body>
</html>

<script>

$(document).on( 'submit', $("#login"), function(event){

    event.preventDefault();


    // Using the core $.ajax() method
    $.ajax({

    // The URL for the request
    url: "users/validate.php",

    // The data to send (will be converted to a query string)
    data: {"username":$('input[name="username"]').val(),
            "password":$('input[name="password"]').val()
    },

    // Whether this is a POST or GET request
    type: "POST",

    // The type of data we expect back
    dataType : "json",
    })
      // Code to run if the request succeeds (is done);
      // The response is passed to the function
      .done(function( data ) {

         $( "<div class=\"content\">").html( JSON.stringify(data) ).appendTo( "body" );
      })
      // Code to run if the request fails; the raw request and
      // status codes are passed to the function
      .fail(function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr.responseText );
      })
      // Code to run regardless of success or failure;
      .always(function( xhr, status ) {

      });
});
</script>