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

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

报告相同问题?

悬赏问题

  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方