dongyou7472 2016-07-27 14:22
浏览 155
已采纳

SyntaxError:解析时意外的输入结束

The following JS code snippet:

    var data_JSON = {
        input: 'test',
        message: 'Sending...'
    };

    $.ajax({
        url: 'main_php.php',
        type: 'POST',
        data: data_JSON,
        dataType : 'json',
        contentType: 'application/json',        
        success: alert(data),       
        error: function (request, status, error) {      
            alert(error);
        }
    }); 

And the following associated PHP code (main_php.php):

if ($_POST){    
    $vals = array(
        'input'     => $input,
        'message'   => $message
    );
    header('Content-Type: application/json');
    echo json_encode($vals);        
}

Always result error (error runs in $.ajax), whatever I tried. In the browser's developer console, I could explore the complete length of the error message:

SyntaxError: Unexpected end of input at parse (native) at ajaxConvert ([...]/jquery-3.0.0.js:8544:19) at done ([...]/jquery-3.0.0.js:9011:15) at XMLHttpRequest. ([...]/jquery-3.0.0.js:9303:9)

Which is exactly the point where the JSON is failed to parse? What is the reason of this error and how can I solve it?

Note: JSON.stringify did not work, if that helps anything.

  • 写回答

1条回答 默认 最新

  • dsb0003795 2016-07-27 15:11
    关注

    try with:

    js:

    var data_JSON = {
        input: 'test',
        message: 'Sending...'
     };
    
    $.ajax({
      url: 'main_php.php',
      method: 'POST',
      data: data_JSON,
      dataType : 'json',
      success: function(data){
        alert(JSON.stringify(data)) ;
      } ,       
      error: function (request, status, error) {      
        alert(error);
      }
    }); 
    

    and php:

    if ($_POST){    
        $vals = array(
          'input'     => $input,
          'message'   => $message
        );
        header('Content-Type: application/json');
        echo json_encode($vals);        
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?