SyntaxError: 无效的正则表达式标志 ajax, Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31377095/
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-08-23 06:37:11  来源:igfitidea点击:

SyntaxError: invalid regular expression flag ajax, Javascript

javascriptjqueryajax

提问by Da Artagnan

This is my controller,

这是我的控制器,

public ActionResult ReturnMethodTest(int id) 
{
    string name = "John";
    return Json( new {data=name});       
}

I am trying to get data from this controller by using code below but I am getting Syntax error.

我试图通过使用下面的代码从这个控制器获取数据,但我得到语法错误.

Can you please tell me what am I doing wrong?

你能告诉我我做错了什么吗?

$.ajax({
        url: @Url.Action("ReturnMethodTest", "HomeController"),
        data: {
            id: 5,
        },
        success: function (data) {
            console.log(data);
        }
    });

回答by Cerbrus

@Url.Actiononly returns the action url's string, without quotes around it.

@Url.Action只返回操作 url 的字符串,不带引号。

You'll need to wrap that url in quotes.

您需要将该网址用引号括起来。

Replace:

代替:

url: @Url.Action("ReturnMethodTest", "HomeController"),

With:

和:

url: '@Url.Action("ReturnMethodTest", "HomeController")',
//   ^                                                 ^

Otherwise, the file returned to the client will contain:

否则,返回给客户端的文件将包含:

url: /HomeController/ReturnMethodTest,

Which isn't valid JS, nor what you want. The replacement gives the following result:

这不是有效的 JS,也不是你想要的。替换结果如下:

url: '/HomeController/ReturnMethodTest',

Which is a perfectly valid JavaScript string.

这是一个完全有效的 JavaScript 字符串。

回答by Aftab Ansari

Please remove the Controllersuffix while specifying in url.

Controller指定时请删除后缀url

Try it this way:

试试这个方法:

url: '@Url.Action("ReturnMethodTest", "Home")'

回答by Noumenon

A Javascript regular expression literallooks like this -- a pattern enclosed between slashes:

一个 Javascript正则表达式文字看起来像这样——一个包含在斜杠之间的模式:

var re = /pattern/flags;

If you interpolate a variable that begins with a slash but do not put quotation marks around it, it will be interpreted as a regular expression, not a string. Another time this comes up is with JSP expression language, where you should write the first, not the second:

如果您插入一个以斜杠开头的变量但没有在它周围加上引号,它将被解释为正则表达式,而不是字符串。另一次出现这种情况是使用 JSP 表达式语言,您应该在其中编写第一个,而不是第二个:

var spinner = "<img src='${contextPath}/images/ajax-loader-small.gif'>"
var spinner = "<img src='" + ${contextPath} + "/images/ajax-loader-small.gif'>"