gpt4 book ai didi

c# - 在 ASP.NET MVC 应用程序中引用 Javascript 文件中路径的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:03 25 4
gpt4 key购买 nike

目前我在我的 js 文件中做的是这个(并且有效):

    var root = "http://mydomain.com";

$.ajax({
type: "POST",
url: root + "/MyController/MyAction",
data: { 'id': myId },
dataType: "html",
success: function (response) {
blah blah...

但是问题是如果有人输入 www.mydomain.com 而不是 mydomain.com,则找不到路径。我尝试遵循这篇文章中的建议:Relative Image URL in Javascript File - ASP.net MVC and IIS 7 ,即将 root 设置为 ../或 document.location.host,但两者都不起作用。

在 js 文件中指定路径( Controller 、图像等中的操作)的正确方法是什么?

谢谢。

最佳答案

在你看来:

<script type="text/javascript">
var url = '<%= Url.Action("MyAction", "MyController") %>';
</script>

并在您的外部 javascript 文件中:

$.ajax({
type: "POST",
url: url,
data: { 'id': postId },
dataType: "html",
success: function (response) {
blah blah...

甚至更好:如果您对现有链接或表单进行 AJAX 化:

<%= Html.ActionLink("foo", "MyAction", "MyController", null, new { id = "foo" })

在你的 javascript 中:

$('#foo').click(function() {
$.ajax({
type: "POST",
url: this.href,
data: { 'id': postId },
dataType: "html",
success: function (response) {
blah blah...
});
return false;
});

关于c# - 在 ASP.NET MVC 应用程序中引用 Javascript 文件中路径的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com