【问题标题】:AJAX Post Error - SyntaxError: Unexpected token R in JSON at position 5AJAX 发布错误 - SyntaxError:JSON 中第 5 位的意外标记 R
【发布时间】:2017-06-15 13:44:15
【问题描述】:

我正在尝试将以下 JSON 文件发送到 AJAX POST 方法。

参见下面的 AJAX 方法:-

$(document).on('submit', '#create-recipe-form', function(){
    // get form data
    var form_data= {
                     "recipe_name":"ghjghjh",
                     "category_name":"Desert",
                     "category_id":"8",
                     "Apple":"Apple",
                     "Carrots":"Carrots",
                     "step1":"ghj",
                     "step2":"",
                     "step3":"",
                     "step4":"",
                     "prep":"6"
                      };

    // submit form data to api
    $.ajax({
        url: "http://localhost:8082/recipe_app/api/recipes/create_recipe.php",
        type : "POST",
        //contentType : 'application/json',
        contentType : 'json',
        data : form_data,
        success : function(result) {

            createRecipeIngredientsForm();

            // recipe was created, go back to recipes list
            //showRecipes();
        },
        error: function(xhr, resp, text) {
            // show error to console
            console.log(xhr, resp, text);
        }
    });

上面的AJAX方法实际上正确调用了.php文件并将数据插入到数据库中。但是返回了一个错误,因此“成功”部分永远不会运行。这太令人沮丧了,有人能解释一下吗?

SyntaxError:JSON 中第 5 位的意外标记 R 在解析() 在 ajaxConvert (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:8754:19) 完成后 (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9222:15) 在 XMLHttpRequest。 (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9514:9)

【问题讨论】:

  • 为什么不发送serializeObject?需要什么字符串化?
  • 从下面的声明var form_data=JSON.stringify($(this).serializeObject());中删除JSON.stringify()

标签: javascript php jquery json ajax


【解决方案1】:

替换你的ajax这一行

form_data=JSON.stringify($(this).serializeObject());

form_data=$(this).serializeObject();

【讨论】:

  • Hi" 感谢您的帮助。现在的问题是我的 PHP 文件中的以下变量现在为空:- $data = json_decode(file_get_contents("php://input"));
猜你喜欢
  • 2018-08-30
  • 1970-01-01
  • 2021-11-28
  • 2020-06-10
  • 2020-10-27
  • 1970-01-01
  • 2016-10-22
  • 2017-08-21
  • 2019-09-21
相关资源
最近更新 更多