【问题标题】:AJAX & PHP response gives "SyntaxError: Unexpected end of JSON input"AJAX 和 PHP 响应给出“SyntaxError:JSON 输入意外结束”
【发布时间】:2018-11-15 16:43:59
【问题描述】:

我正在使用 AJAX 调用验证脚本。在$response 返回时,我不断收到错误SyntaxError: Unexpected end of JSON input。如果我没有返回格式正确为 JSON 的数据,我不会感到惊讶,但现在我已经在 J​​SON 解析器中运行了响应 { "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.");
    }
?>

【问题讨论】:

  • 可能不是问题所在,但您应该去掉顶部多余的换行符 -> 删除 ?&gt; 直到 &lt;?php。和尾随的?&gt;
  • echo json_encode("No data."); 将不是有效的 json,而只是一个字符串
  • json_encode("No data."); 将给您"No data."JSON.parse 将毫无问题地接受并给您No data.
  • $(document).on( 'submit', $("#login") 应该是$(document).on( 'submit', "#login"
  • validate.php 期待的是普通表单数据,而不是 JSON 对象。

标签: javascript php json ajax


【解决方案1】:

我在那里看到了几个问题

首先,您发送的数据格式错误,并且创建一个 json 字符串然后将其解析为一个对象是不必要的,因为您可以首先创建对象。

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

其次,由于您的数据格式错误,$validation-&gt;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){

【讨论】:

  • “创建一个 json 字符串然后将其解析为一个对象是不必要的”......我会更进一步说这只是疯狂:-)
【解决方案2】:

您可能希望在 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();
}

【讨论】:

  • 如果输出中有多余的字符,你会得到一个不同的错误,比如Uncaught SyntaxError: Unexpected token . in JSON at position 10
【解决方案3】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2020-08-17
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多