javascript - 由于 json,Ajax 表单无法工作(解析器错误抛出 : SyntaxError: JSON. 解析:JSON 数据的第 1 行第 1 列处的数据意外结束)

标签 javascript php jquery json ajax

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

index.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');
  }
});
  });
});

sendMail.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 ERROR

UPLOADING DATA IS FINE

最佳答案

您基本上需要为表单数据使用不同的序列化方法。这里提到了类似的东西:Convert form data to JSON object

下面是您应该用于 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/

希望这有帮助!

关于javascript - 由于 json,Ajax 表单无法工作(解析器错误抛出 : SyntaxError: JSON. 解析:JSON 数据的第 1 行第 1 列处的数据意外结束),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019379/

相关文章:

javascript - 禁用javascript时禁用提交按钮

javascript - 如何模仿 JavaScript 对象或数组中缺失的属性或元素?

php - 在 php 和 mysql 中更新/编辑表单字段的最佳实践是什么?

javascript - 如何使用 Jquery 将图像添加到输入时创建的每条消息中?

javascript - 将焦点设置在带有错误消息的第一个输入元素上,并将包含它的 TabStrip 的选项卡设置为事件

javascript - 使用大数据集中较旧的/未发布的数据进行刷新

javascript - 由于 UTC,Angular JS 中的 DatePicker 错误

php - 在后台 iOS GCM 中未收到推送通知

php - 将数组保存到数据库 mysql/php

jquery - 文件丢失在文件系统中,捕获表单提交