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

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);        
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效