簡體   English   中英

Ajax 無法將數據作為 json 發送到 php 沒有錯誤

[英]Ajax can't send data to php as json without error

當我想將數據作為數據類型 json 發送時,它會響應此錯誤:SyntaxError: Unexpected token < in JSON at position 0

當我嘗試將數據作為數據類型文本發送時,它成功地將數據發送到 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>";
}

嘗試這個

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);
  }
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM