javascript jQuery post 导致 Uncaught SyntaxError: Unexpected token :

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5115612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:00:01  来源:igfitidea点击:

jQuery post causes Uncaught SyntaxError: Unexpected token :

javascriptasp.net-mvcjquery

提问by Chris

I found a bunch of similar questions here but after 3 hours of reading them and trying stuff, I am posting my own. I apologize for the duplication, but I just don't know what's going on here.

我在这里发现了一堆类似的问题,但是在阅读了 3 个小时并尝试了一些东西之后,我发布了自己的问题。我为重复道歉,但我只是不知道这里发生了什么。

So I have this javascript function:

所以我有这个javascript函数:

function saveSetting(settingName, settingValue) {
    $.post(
        appUrl + "Account/SaveSetting",
        { settingName: settingName, settingValue: settingValue },
        function (data) {
            alert(data.Result);
        },
        "json"
    );
}

which I call like this:

我这样称呼它:

saveSetting("bookFontSize", fontSize);

where fontSize is "10.5" or something similar.

其中 fontSize 是“10.5”或类似的东西。

Chrome reports the post headers like this:

Chrome 报告这样的帖子标题:

Request URL:http://localhost:1227/Account/SaveSetting?callback=jQuery151022712289774790406_1298625531801
Request Method:POST
Status Code:200 OK
Request Headers
Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:42
Content-Type:application/x-www-form-urlencoded
Cookie:ASP.NET_SessionId=jwpzp4okerckuh2bhkl2pnwu; .ASPXAUTH=429EEA1CFBFD9D5702011C59F77F18F8DAEEEB412314D608E86289779DF8ED9C80C6E0370B7108D68C44B088C7CB6998F34C59DDCFF8EA9D4A556495F5D40DF21737392DCF5942F73726882BEC354C35599864F751751FD458473FA4541AF25294F7E16DC00AABD4DEC43B321B0ECCBF195FD419C3BC912017275FC478A27F0C12A28D124A663EA5F19E5AEFFB276603
Host:localhost:1227
Origin:http://localhost:1227
Referer:http://localhost:1227/Read/116/1
User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13
X-Requested-With:XMLHttpRequest
Query String Parameters
callback:jQuery151022712289774790406_1298625531801
Form Data
settingName:bookFontSize
settingValue:10.5
Response Headers
Cache-Control:private, s-maxage=0
Connection:Close
Content-Length:38
Content-Type:application/json; charset=utf-8
Date:Fri, 25 Feb 2011 09:18:53 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0

That goes to a C# / ASP.NET MVC3 action that looks like this:

转到 C#/ASP.NET MVC3 操作,如下所示:

[Authorize]
public JsonResult SaveSetting(string settingName, string settingValue)
{
    try
    {
        repository.SaveSettingForUser(CurrentUser, settingName, settingValue);
    }
    catch (Exception ex)
    {
        return Json(new { Result = CurrentUser.IsAdmin() ? "Failed :" + ex.Message : "Failed" });
    }
    return Json(new { Result = string.Format("Set {0} to {1}.", settingName, settingValue) });
}

which, according to chrome, returns this:

根据 chrome,它返回这个:

{"Result":"Set bookFontSize to 10.5."}

which looks like legitimate json to me. However, I get this error in chrome:

对我来说这看起来像是合法的 json。但是,我在 chrome 中收到此错误:

Uncaught SyntaxError: Unexpected token :

and this one in IE 7, and 8:

而这个在 IE 7 和 8 中:

An error has occurred in the script on this page.
Line: 67456553
Char: 10
Error: Expected ';'
Code: 0
URL: http://localhost:1227/Read/116/1

I definitely do not have 67 million lines of code :)

我绝对没有 6700 万行代码 :)

Anyway, does anyone know what the heck is going on here? My alert does not run. IE never actually gets the request out, but Chrome does.

无论如何,有人知道这里发生了什么吗?我的警报没有运行。IE 从未真正获取过请求,但 Chrome 却可以。

I think this function actually worked with a previous version of jQuery a long time ago, with the setting $.ajaxSettings.traditional = true, but now it doesn't work (jQuery 1.5.1) with or without that setting.

我认为这个函数很久以前实际上可以与以前版本的 jQuery 一起使用,带有设置$.ajaxSettings.traditional = true,但现在无论是否有该设置,它都不起作用(jQuery 1.5.1)。

Update: I got it working. I stepped through the javascript with the debugger. For some reason, during the .ajax() call in jQuery, it was stepping into jquery.validate.js. Why would it do that? I had the file included, but was not using it anywhere. I eliminated the error by simply no longer referencing jquery.validate.js. But this kind of sucks, because what if I want to use the validation features in the future?

更新:我让它工作了。我使用调试器逐步完成了 javascript。出于某种原因,在 jQuery 中的 .ajax() 调用期间,它进入了 jquery.validate.js。为什么会那样做?我包含了该文件,但没有在任何地方使用它。我通过不再引用 jquery.validate.js 来消除错误。但是这种方式很糟糕,因为如果我将来想使用验证功能怎么办?

So my question now is "Why does having jquery.validate.js in my project screw everything up?"

所以我现在的问题是“为什么我的项目中有 jquery.validate.js 把一切都搞砸了?”

Update 2: There is a bug in jquery.validate.js, which has now been fixed in a fork of that project on github. See my answer for details. I was not even usingthe validation features of that file, merely including it in the page for later use. It gets in the way and breaks things. Note from the author of jquery.validate.js regarding the fix: "Fixes jQuery 1.5- code by using jQuery.ajaxSettings and not window.ajaxSettings (yeah, that was dumb)."

更新 2:jquery.validate.js 中存在一个错误,现已在 github 上该项目的一个分支中修复。详情请看我的回答。我什至没有使用该文件的验证功能,只是将其包含在页面中供以后使用。它会妨碍并破坏事物。jquery.validate.js 的作者关于修复的注释:“通过使用 jQuery.ajaxSettings 而不是 window.ajaxSettings 修复 jQuery 1.5 代码(是的,那是愚蠢的)。”

回答by Chris

I figured it out!!!

我想到了!!!

It's a bug in jquery.validate.js. It's repeated and documented here: http://bugs.jquery.com/ticket/8064

这是 jquery.validate.js 中的一个错误。这里重复并记录在案:http: //bugs.jquery.com/ticket/8064

The author has addressed the issue on February 2, 2011, but this fix has not yet made it into an official release of the plugin (as of February 25, 2011 and jQuery Validate 1.7). If you would like jQuery 1.5+ JSON to work while using jquery validation, you should download the patched validation plugin.

作者已于 2011 年 2 月 2 日解决了该问题,但此修复程序尚未使其成为插件的正式版本(截至 2011 年 2 月 25 日和 jQuery Validate 1.7)。如果您希望 jQuery 1.5+ JSON 在使用 jquery 验证时工作,您应该下载补丁验证插件。

https://github.com/jaubourg/jquery-validation/raw/master/jquery.validate.jshttps://github.com/jaubourg/jquery-validation/raw/master/jquery.validate.min.js

https://github.com/jaubourg/jquery-validation/raw/master/jquery.validate.js https://github.com/jaubourg/jquery-validation/raw/master/jquery.validate.min.js

If you are here from google and the above links don't work anymore, upgrading to a version of validate that is greater than 1.7 will probably work. Alternatively, go here https://github.com/jaubourg/jquery-validationand grab the latest version from the repository.

如果您从 google 来到这里并且上述链接不再有效,则升级到大于 1.7 的验证版本可能会起作用。或者,到这里https://github.com/jaubourg/jquery-validation并从存储库中获取最新版本。

2011-08-31 Update: It looks like they don't use that GitHub link anymore. I thinkthis is what you need.

2011-08-31 更新:看起来他们不再使用那个 GitHub 链接了。认为这就是你所需要的。

回答by profanis

You declared the post as json, so the result must be auto evaluated.

您将帖子声明为 json,因此必须自动评估结果。

Nevertheless, try to evaluate the result before the alert on inside the brackets of the alert

尽管如此,请尝试在警报括号内的警报之前评估结果

eval(data.Result)

回答by Adolph Trudeau

Could it be that the object key names are being set dynamically in some browsers? Try changing saveSetting to the following:

可能是在某些浏览器中动态设置了对象键名称?尝试将 saveSetting 更改为以下内容:

function saveSetting(settingName, settingValue) {
    $.post(
        appUrl + "Account/SaveSetting",
        { "settingName": settingName, "settingValue": settingValue },
        function (data) {
            alert(data.Result);
        },
        "json"
    );
}

Or perhaps changing the argument name to something other than the object key name:

或者可能将参数名称更改为对象键名称以外的名称:

function saveSetting(settingNameArg, settingValueArg) {
    $.post(
        appUrl + "Account/SaveSetting",
        { settingName: settingNameArg, settingValue: settingValueArg },
        function (data) {
            alert(data.Result);
        },
        "json"
    );
}

回答by Gutzofter

You are returning incorrect JSON from server. Your returned JSON has some control character in the Result. Would recommend sending a string without new String.format

您正在从服务器返回错误的 JSON。您返回的 JSON 在Result. 建议发送一个不带的字符串new String.format

回答by Darin Dimitrov

Never hardcode urls. Always use url helpers when dealing with urls. Also don't provide absolute urls as jQuery thinks it is JSONP (notice the callback=jQuery151022712289774790406_1298625531801parameter in your request) while the response is only JSON:

永远不要硬编码网址。处理 url 时始终使用 url helper。也不要提供绝对网址,因为 jQuery 认为它是 JSONP(注意callback=jQuery151022712289774790406_1298625531801您请求中的参数)而响应只是 JSON:

function saveSetting(settingNameArg, settingValueArg) {
    $.post(
        '<%= Url.Action("SaveSetting", "Account") %>',
        { settingName: settingNameArg, settingValue: settingValueArg },
        function (data) {
            alert(data.Result);
        },
        'json'
    );
}

Also notice that your function arguments are called settingNameArgand settingValueArgwhereas inyour code you were using settingNameand settingValue.

还要注意你的函数参数被调用settingNameArgsettingValueArg而在你的代码中你使用的是settingNameand settingValue

回答by Ben Pretorius

I am using this:

我正在使用这个:

// The Actionresult is being called by an Ajax Call:
    public ActionResult SomePartial(Object model)
    {
    return Json(new { state="Success", date="some data" });
    }

//OnSuccess of the Ajax Call:
    function OnSuccess(ajaxContext) {
    var result = eval(ajaxContext);
    if (result.state == "Success") {
    console.log(result.data)
    }
            else {
                // ERRORS
            }

        }

this returns a valid json object and displays it:)

这将返回一个有效的 json 对象并显示它:)

also nb to validate your json http://jsonlint.com/

也 nb 验证您的 json http://jsonlint.com/