【问题标题】:Ajax form not working because of json (parsererror thrown: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data)由于 json 导致 Ajax 表单无法正常工作(引发的解析器错误:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data)
【发布时间】:2019-01-31 19:34:01
【问题描述】:

我知道这个问题已经被问过很多次了,但是我已经尝试了所有的解决方案,但对我没有任何效果,所以我的问题是我无法使用 ajax 从服务器加载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>

script.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 负载是什么?
  • 我正在尝试发送$data['signal']$data['res-msg']
  • 当您有dataType: 'JSON' 时,您不需要var response=parseJSON(res); ... .ajax 方法已经返回res 作为要在success 回调中使用的对象。同样由于告诉 ajax 会发生什么,你在 php 端真的不需要header("Content-Type: application/json", true);
  • @IncredibleHat 我已经删除了你说的所有代码,但仍然无法正常工作

标签: javascript php jquery json ajax


【解决方案1】:

您的表单数据基本上需要不同的序列化方法。这里提到了类似的东西: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/

希望这会有所帮助!

【讨论】:

  • 这是 404 错误,因为它没有找到 .php 文件。 :) 我刚刚更新了那里的代码供您参考:jsfiddle.net/7jm568ay/6
【解决方案2】:

我已经测试了你的代码,我认为你的 php 脚本 (sendMail.php) 的问题在第 2 行 (if (isset($_POST['mail-submit']))),其中 "mail-submit"未序列化(**由于序列化不包括提交按钮值),这就是为什么代码没有首先满足 if 条件并给出错误的原因。所以,如果你使用“mail-email”而不是“mail-submit”((if (isset($_POST['mail-email'])))),我认为它会起作用。

或者你可以像下面这样改变你的脚本:

index.php

        <div>
        <input type="hidden" id="mail-submit-hidden" name="mail-submit" value="0" >
        <button id="mail-submit" type="submit">BOOK A TABLE</button>
    </div>
</form>

script.js

event.preventDefault();
$('#mail-submit-hidden').val('1');
$.ajax({

请试一试。

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2018-08-24
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多