【问题标题】:Ajax can't send data to php as json without errorAjax 无法将数据作为 json 发送到 php 而不会出错
【发布时间】:2020-10-01 08:54:37
【问题描述】:

当我想以数据类型 json 发送数据时,它会响应此错误: SyntaxError: 意外的标记

当我尝试将数据作为数据类型文本发送时,它成功地将数据发送到 php,但我的 php 不会响应。

ajax/js 作为数据类型 json:

let form = $("#form");

$("#form").on("submit", function(e) {
                          
  e.preventDefault();
                          

  $.ajax({
    url: "test.php",
    method: "POST",
    dataType: "json",
    data: {
       test: 1
    },
  success: function (r) {
    console.log("!!!");
  },
  error: function(jqXHR, textStatus, errorMessage) {
    console.log(errorMessage);
  }
  });

});

ajax/js 作为数据类型正常:

let form = $("#form");

$("#form").on("submit", function(e) {
                          
   e.preventDefault();
                     
   $.ajax({
      url: "test.php",
      method: "POST",
      data: form.serialize(),
      success: function (r) {
        console.log("!!!");
      },
      error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage);
      }
   });

});

php代码:

if(isset($_POST["test"])){
   echo "<script>console.log('works');</script>";
}

【问题讨论】:

  • 好吧,&lt;script&gt;console.log('works');&lt;/script&gt; 只是 not 有效的 JSON。
  • 我删除了这个 echo 脚本。错误是一样的,但现在“在位置 2”。
  • 那么你的脚本必须仍然响应一些东西,那不是有效的 JSON。首先,使用浏览器开发工具(网络面板)检查实际响应是什么。
  • 该死,为什么 content-type: text/html... 任何解决方案?还是这不是问题?
  • dataType 设置 response 对象的数据类型,因此您的 ajax 调用需要从 PHP 返回一个 json 对象,但您回显了一些 &lt;script&gt; 字符串。尝试类似echo json_encode(['myVar' =&gt; 'myValue']);

标签: javascript php jquery json ajax


【解决方案1】:

试试这个

var ob = {
       test: 1
    };
$.ajax({
    url: "test.php",
    method: "POST",
    dataType: "json",
    contentType: 'application/json',
    data:JSON.stringify(ob),
  success: function (r) {
    console.log("!!!");
  },
  error: function(jqXHR, textStatus, errorMessage) {
    console.log(errorMessage);
  }
  });

【讨论】:

    猜你喜欢
    • 2020-10-18
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-07-09
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    相关资源
    最近更新 更多