jquery AJAX 调用MVC控制器- URL问题

q5iwbnjs  于 2022-12-22  发布在  jQuery
关注(0)|答案(6)|浏览(191)

我已经看了以前发布的jQuery/MVC问题,还没有找到可行的答案。
下面是一段JavaScript代码:

$.ajax({
    type: "POST",
    url: '@Url.Action("Search","Controller")',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

调用URL时,帖子如下所示:

NetworkError: 500 Internal Server Error - <a href="http://localhost/Web/Navigation/@Url.Action(%22Search%22,%22Chat%22)"></a>

为什么它会这样返回(它背后的逻辑),解决方案是什么?
P.S.:其他信息:%22是〈〈"〉〉字符的URL编码引用

rlcwz9us

rlcwz9us1#

为了使其工作,JavaScript必须放置在Razor视图中,以便行

@Url.Action("Action","Controller")

由Razor解析并替换真实的值。
如果您不想将JavaScript移动到视图中,您可以考虑在视图中创建一个设置对象,然后从JavaScript文件中引用该对象。
例如:

var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'
}

并在您的.js文件中:

$.ajax({
    type: "POST",
    url: MyAppUrlSettings.MyUsefulUrl,
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

或者看看在HtmlHelpers中的Ajax方法中勒韦林框架的built,它允许您在不使用JS代码“污染”视图的情况下实现相同的效果。

epggiuax

epggiuax2#

代码示例中存在类型错误。忘记了success后面的花括号

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

2sbarzqh

2sbarzqh3#

一个不涉及视图的好方法是:

$.ajax({
    type: "POST",
    url: '/Controller/Search',
    data: { queryString: searchVal },
    success: function (data) {
      alert("here" + data.d.toString());
    }
});

这将尝试POST到URL:
http://domain/Controller/Search(您要使用的操作的正确URL)”

fcipmucu

fcipmucu4#

Rob's answer开始,我目前使用的语法如下,由于这个问题已经受到了很多关注,我决定与大家分享:

var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
  $.ajax({
   type: "POST",
   url: requrl,
   data: "{queryString:'" + searchVal + "'}",
   contentType: "application/json; charset=utf-8",
   dataType: "html",
   success: function (data) {
   alert("here" + data.d.toString());
   }
  });
xoefb8l8

xoefb8l85#

mihai-labo's答案开始,为什么不完全跳过声明requrl变量,直接将url生成代码放在“url:“前面,例如:

$.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});
qjp7pelc

qjp7pelc6#

访问URL的简单方法尝试此代码

$.ajax({
     type: "POST",
      url: '/Controller/Search', 
     data: "{queryString:'" + searchVal + "'}",
     contentType: "application/json; charset=utf-8",
     dataType: "html",
     success: function (data) {
     alert("here" + data.d.toString());
    });

相关问题