简体   繁体   English

AJAX发布错误-SyntaxError:JSON位置5出现意外的令牌R

[英]AJAX Post Error - SyntaxError: Unexpected token R in JSON at position 5

I am trying to send the following JSON file to an AJAX POST method. 我正在尝试将以下JSON文件发送到AJAX POST方法。

See AJAX method below:- 请参阅下面的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);
        }
    });

The above AJAX method actually correctly calls the .php file and the data is inserted into the database. 上面的AJAX方法实际上正确地调用了.php文件,并且数据已插入数据库中。 But there is an error returned and therefore the 'success' section never runs. 但是返回了错误,因此“成功”部分永远不会运行。 This is so frustrating, can anybody shed any light? 这太令人沮丧了,有人可以照亮吗?

SyntaxError: Unexpected token R in JSON at position 5 at parse () at ajaxConvert ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:8754:19 ) at done ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9222:15 ) at XMLHttpRequest. SyntaxError:ajaxConvert( http:// localhost:8082 / recipe_app / app / assets / js / jquery-3.2.1.js:8754:19 )在parse()处位置5处的JSON中意外的令牌R( http: //Http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9222:15 )。 ( http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9514:9 ) http:// localhost:8082 / recipe_app / app / assets / js / jquery-3.2.1.js:9514:9

replace this line of your ajax 替换此行的ajax

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

to

form_data=$(this).serializeObject();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM