首页 > 解决方案 > 由于 json 导致 Ajax 表单无法正常工作(引发的解析器错误:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data)

问题描述

我知道这个问题之前已经被问了很多,但是我已经尝试了所有的解决方案,但对我没有任何效果,所以我的问题是我无法json使用 ajax 从服务器加载响应我有script.js一个 js 文件夹和我sendMail.php的包含文件夹当我提交一些信息时,index.php它也在根文件夹中,状态为 200 表示一切正常,但由于json响应,我无法用我的 php 代码检查它们

索引.php

<!DOCTYPE html>
<html>
<head>
    <title>Booking</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
    <form action="includes/sendMail.php"  method="POST" name="reservation-form"  id="reservation-form">
        <div>
            <select class="select-dropbox" name="mail-hour">
                <option value="" disabled selected>Hour</option>
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </div>

        <div>
            <input type="text" name="mail-phone" placeholder="Phone Number"
            >
        </div>
        <div>
            <input type="text" name="mail-email" placeholder="Email Address" >
        </div>
        <div>
            <textarea name="mail-msg" placeholder="Your Message"  ></textarea>
        </div>
        <div id="check-form">
        </div>
        <div>
            <button id="mail-submit" name="mail-submit" type="submit">BOOK A TABLE</button>
        </div>
    </form>
</body>
</html>

脚本.js

$(document).ready(function(){
  $('#mail-submit').click(function(event){
    event.preventDefault();
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: 'JSON',
      url: 'includes/sendMail.php',
      type: 'POST',
      data: $('#reservation-form').serialize(),
      beforeSend: function(xhr){
        $('#mail-submit').html('SENDING...');
      },
      success: function(response){
       if(respo,se){
        alert(response);
        if(response['signal'] == 'ok'){
         $('#check-form').html('<div>'+ response['res-msg']  +'</div>');

       }
       else{
        $('#check-form').html('<div>'+ response['res-msg'] +'</div>');
      }
    }
  },
  error: function(xhr, status, thrown){
    alert("xhr: "+xhr+" status: "+status+" thrown: "+thrown);
    $('#check-form').html('<div>An Error occurs. Please try again.</div>');
  },
  complete: function(){

    $('#mail-submit').html('BOOK A TABLE');
  }
});
  });
});

发送邮件.php

<?php
if (isset($_POST['mail-submit'])) {
    $hour = trim($_POST['mail-hour']);
    $phone = trim($_POST['mail-phone']);
    $email = trim($_POST['mail-email']);
    $message = trim($_POST['mail-msg']);
    if($hour != null && $phone != null && $email != null){
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $signal = 'bad';
            $msg = 'Invalid email. Please check';
        }
        else {
            $signal = 'ok';
            $msg = 'Form submitted';
        }
    }
    else{
        $signal = 'bad';
        $msg = 'Please fill in all the fields.';
    }
    $data = array(
        'signal' => $signal,
        'res-msg' => $msg
    );
    echo json_encode($data);
}   
?>

JSON错误

上传数据没问题

标签: javascriptphpjqueryjsonajax

解决方案


您基本上需要为表单数据使用不同的序列化方法。这里提到了类似的东西:将表单数据转换为 JSON 对象

以下是您应该用于 JS 的代码。注意使用的是serializeObject而不是serialize。我无法执行 PHP 代码,但您面临的序列化问题现在将得到修复,这也应该可以修复您的 PHP 代码。

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


$(document).ready(function(){
  $('#mail-submit').click(function(event){
    event.preventDefault();
    var d = $('#reservation-form').serializeObject();
    d = JSON.stringify(d);
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: 'JSON',
      url: 'includes/sendMail.php',
      type: 'POST',
      data: d,
      beforeSend: function(xhr){
        $('#mail-submit').html('SENDING...');
      },
      success: function(res){
       if(res){
        var response=parseJSON(res);
        alert(response);
        if(response['signal'] == 'ok'){
         $('#check-form').html('<div>'+ response['res-msg']  +'</div>');

       }
       else{
        $('#check-form').html('<div>'+ response['res-msg'] +'</div>');
      }
    }
  },
  error: function(xhr, status, thrown){
    alert("xhr: "+xhr+" status: "+status+" thrown: "+thrown);
    $('#check-form').html('<div>An Error occurs. Please try again.</div>');
  },
  complete: function(){

    $('#mail-submit').html('BOOK A TABLE');
  }
});
  });
});

在这里工作的 HTML/JS 代码:https ://jsfiddle.net/7jm568ay/5/

希望这可以帮助!


推荐阅读