如何使AJAX调用
问题描述:
我知道这个问题已经回答之前,但我无法击中我的控制器内的行动。如何使AJAX调用
这里是行动
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
在我的脚本:
$.ajax({
type: 'GET',
url: '@Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
使用招我可以打GetUpdate但是从浏览器中的Ajax调用失败。我是否正确访问网址?
更新: 以下是错误消息: “NetworkError:404未找到 - 协议://本地主机:port/Controller/@Url.Action(%22GetUpdate%22)”
以下作品通过小提琴: 协议://本地主机:端口/控制器/ GetUpdate
答
剃刀代码(C#和所有其他服务器端脚本)只从.cshtml
文件执行,因此C#和剃刀不能在.js
文件中使用。 '@Url.Action("GetUpdate")'
不会生成一个URL,它只是一个字符串,因此您正试图请求protocol://domain:port/[email protected]("GetUpdate")
哪个不是存在。
这里是你可以做什么:
- 在
.cshtml
文件可以将生成的URL存储在一个JavaScript变量,并传递给外部JS文件。 - 您可以将您的外部JavaScript移动到
.cshtml
文件,以便您可以使用Razor。 - 使用相对路径字符串像
/Controller/GetUpdate
我推荐的第一个。
答
你可以试试这个出,其中_ApplicationPath是协议://本地主机:端口/
$.ajax({ type: 'GET', url: _ApplicationPath + "/ControllerName/GetUpdate", dataType: 'json', success: function (constraints) { alert("Application updated"); }, error: function (ex) { alert('Failed to retrieve update.' + ex); } });
尝试设置的URL'GetUpdate'。另外,请注意相对路径。 – Brandon 2014-10-12 13:16:19
对不起,你是什么意思?我怎么做?我以为@ url.Action产生了相对路径?! – user3320502 2014-10-12 13:20:31
我觉得你错过了定义'GetUpdate'的控制器类名称 – 2014-10-12 13:30:48