简体   繁体   English

Ajax调用失败,错误为“ SyntaxError:JSON.parse错误:位置0意外输入”

[英]Ajax Call Failing with Error “SyntaxError: JSON.parse Error: Unexpected input at position:0”

I am having an issue making a successful call to my controller from view with Ajax Post method. 我在使用Ajax Post方法从视图成功调用我的控制器时遇到问题。

Here is ajax call: 这是ajax调用:

            var Model =
            {
                Ration: "123",
                Batch: "2323",
                IngredientAmountList: "34",
                InputAmount: "35",
                RationTotalWeight:"55"
            };

        $.ajax({
            url: '@Url.Action("AjaxCall", "Producer")',
            type: "POST",
            data: JSON.stringify(Model),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log("success");
                console.log(data);
                console.log(data.length);
            },

            failure: function (data) {
                console.log("failure");
            },
            error: function (jqxhr, textStatus, errorThrown) {
                console.log(jqxhr);
                console.log(textStatus);
                console.log(errorThrown);
            },

        });

Here is Controller method receiving Ajax call: 这是接收Ajax调用的Controller方法:

    [HttpPost]
    public JsonResult AjaxCall()
    {
        //var modelTest = Model;

        return new JsonResult();
    }

The web browser will print out the error from the ajax method error function. Web浏览器将从ajax方法错误功能中打印出错误。 Interesting to me is that if a breakpoint is set on AjaxCall() in the controller, it will hit the breakpoint. 对我来说有趣的是,如果在控制器的AjaxCall()上设置了断点,它将达到断点。 If AjaxCall() is given a string argument AjaxCall(string test){} it will still hit breakpoint and still fail. 如果给AjaxCall()一个字符串参数AjaxCall(string test){},它仍然会达到断点并且仍然会失败。 If AjaxCall() is given model argument as I want to do in the end, ie AjaxCall(MyModel model){} it doesn't even hit the breakpoint in the controller. 如果像我最后想要的那样给AjaxCall()提供了模型参数,即AjaxCall(MyModel model){},它甚至没有达到控制器中的断点。

The model being passed in the for the ajax call possesses all the public getter/setter properties of the actual model. 在ajax调用中传递的模型具有实际模型的所有公共getter / setter属性。

The error that the ajax API is printing out is "SyntaxError: JSON.parse Error: Unexpected input at position:0", this is also something I am not finding anything on online. Ajax API打印出的错误是“ SyntaxError:JSON.parse错误:位置0意外输入”,这也是我在网上找不到任何内容的原因。

Thanks for any possible advice 感谢您的任何建议

My guess is that you do not pass valid data from your controller. 我的猜测是您不会从控制器传递有效数据。 Try to pass an empty js object as JSON result return '{}' . 尝试传递一个空的js对象作为JSON结果return '{}' See the code below. 请参见下面的代码。

   [HttpPost]
public JsonResult AjaxCall()
{
    //var modelTest = Model;

    return '{}';
}

If this does not return an error then the data you are passing as a result is not valid JSON data. 如果这没有返回错误,那么您要传递的数据将是无效的JSON数据。

Try it like this: 像这样尝试:

var Model =
            {
                Ration: "123",
                Batch: "2323",
                IngredientAmountList: "34",
                InputAmount: "35",
                RationTotalWeight:"55"
            };

        $.ajax({
            url: '@Url.Action("AjaxCall", "Producer")',
            type: "POST",
            dataType: "json",
            data: { myAjaxModel: Model }, //Make sure data holds name of parameter passed to controller method
            //I removed the contentType and use ajax's default object type, pass the model as a Model object to controller
            success: function (data) {
                const jsonResult = JSON.parse(data); //parse the response
                console.log("success");
                console.log(data);
                console.log(data.length);
            },

            failure: function (data) {
                console.log("failure");
            },
            error: function (jqxhr, textStatus, errorThrown) {
                console.log(jqxhr);
                console.log(textStatus);
                console.log(errorThrown);
            },

        });

       //Changed this to return a string, which is the json version of model
       [HttpPost]
       public string AjaxCall(Model myAjaxModel)
       {
            var modelTest = myAjaxModel;
            //Create a javascript serializer to serialize your model
            System.Web.Script.Serialization.JavascriptSerializer jss = new System.Web.Script.Serialization.JavascriptSerializer();
            //Do your model updating, then return the updated version
            //Return a Json version of the model
            return jss.Serialize(modelTest);
       }

I believe the issue was a combination of the complexity of my original model and the return value of the controller method. 我认为问题是原始模型的复杂性和控制器方法的返回值共同造成的。

My ajax call in the view ended up looking like 我在视图中的ajax调用最终看起来像

        var ajaxModelData = {
            Name: "Bob",
            City: "Mpls"
        };

        $.ajax({
            url: '@Url.Action("AjaxCall", "Producer")',
            type: "POST",
            data: ajaxModelData,      //modelJson, //JSON.stringify(Model),

            success: function (data) {
                console.log("success");
                console.log(data);
                console.log(data.City);
                console.log(data.Name);
            },

            failure: function (data) {
                console.log("failure");
            },
            error: function (jqxhr, textStatus, errorThrown) {
                console.log(jqxhr);
                console.log(textStatus);
                console.log(errorThrown);
            },

        });

and my Controller method looks like 和我的Controller方法看起来像

    [HttpPost]
    public ActionResult AjaxCall(RationGridAjaxModel data)
    {         

        data.City += " this will be added and printed in web console from ajax success call";
        return Json(data, JsonRequestBehavior.AllowGet);

    }

and the RationGridAjaxModel object being accepted by my controller method is actually just a new model class I made to hold the values I require for server-side updates. 我的控制器方法接受的RationGridAjaxModel对象实际上只是我制作的一个新模型类,用来保存服务器端更新所需的值。 I am not sure why I could not do it with my original model, breakpoints on the controller's method would never be hit when trying to pass in my original model. 我不确定为什么不能用原始模型做到这一点,当尝试传递原始模型时,控制器方法的断点将永远不会被击中。 I'm guessing it's an issue with certain methods or dependencies that exist in the original model. 我猜这是原始模型中存在的某些方法或依赖项的问题。

暂无
暂无

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

相关问题 SyntaxError: JSON.parse: AJAX 调用中出现意外字符错误 - SyntaxError: JSON.parse: unexpected character error in AJAX call JSON.parse() 导致错误:`SyntaxError: Unexpected token in JSON at position 0` - JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0` JSON.parse() 错误 SyntaxError: Unexpected token &lt; in JSON at position 0 - JSON.parse() Error SyntaxError: Unexpected token < in JSON at position 0 AJAX请求错误:“SyntaxError:JSON.parse:unexpected character” - AJAX request error: “SyntaxError: JSON.parse: unexpected character” localStorage 和 JSON.parse 的问题,错误:Uncaught SyntaxError: Unexpected token [ in JSON at position 1430 - problem with localStorage and JSON.parse, error : Uncaught SyntaxError: Unexpected token [ in JSON at position 1430 角向Django推送用户登录表单错误“ SyntaxError:JSON中的意外令牌&lt;在JSON.parse(位置2) <anonymous> )” - Angular push to Django for user login form error “SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>)” 我正在使用Ionic并收到错误消息:SyntaxError:JSON中的意外标记&lt;在JSON.parse位置0处( <anonymous> ) - I am using ionic and getting an error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) JSON.parse 错误(未捕获的 SyntaxError:JSON 中的意外标记 o 在 position 1) - JSON.parse error (Uncaught SyntaxError: Unexpected token o in JSON at position 1) 具有相同数据的Ajax错误(parsererror:SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符) - Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data) AJAX SyntaxError:JSON.parse:意外字符 - AJAX SyntaxError: JSON.parse: unexpected character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM