Ajax调用单独的js文件

时间:2013-08-17 14:46:04

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我可以在* .cshtml文件上使用ajax调用,如下所示。它工作正常。

$.ajax({
    url: '@Url.Action("GetAllBooks", "Book")',
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    success: function (data) {
        self.Books(data); //Put the response in ObservableArray
    }
});

但是如何在单独的* .js文件中调用相同的方法?当我使用上面的代码时它不起作用?

3 个答案:

答案 0 :(得分:5)

CSHTML(我更喜欢标签输入):

@* without the attribute 'name' *@
<input type="hidden" value="@Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks" />

@* or *@

<div style="display:none;" data-url="@Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks"></div>

JS:

var url = $('#UrlBookGetAllBooks').val();
//or for tag div
var url = $('#UrlBookGetAllBooks').data('url');

$.ajax({
    url: url,
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    success: function (data) {
        self.Books(data); //Put the response in ObservableArray
    }
});

答案 1 :(得分:4)

HTML - 包含数据属性

<div id="ExampleDiv" 
    data-url = "@Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>

HTML - 选项2

<div id="ExampleDiv" 
    url-Val = "@Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>

JQuery - 包含数据属性

var Url_Value = $('#ExampleDiv').data('url');

JQuery - 选项2

var Url_Value = $('#ExampleDiv').attr('url-Val');

Ajax Call

$.ajax({
    url: Url_Value,
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    success: function (data) {
        self.Books(data); //Put the response in ObservableArray
    }
});

答案 2 :(得分:1)

对于这样的解决方案,我建议您在BookController上创建一个带有“JavascriptActionResult”或新“JavascriptActionResult”的JavascriptController以及输出所需javascript的视图。这样你就可以使用razor动态编写Javascript,并且还保证将遵循MVC的Route Pattern行为。完成所有设置后,页面将为:

<script type="text/javascript" src="@Url.Action("GetAllBooksJS","Book")"></script>

PS:MVC中没有原生的JavascriptActionResult,但您可以扩展ActionResult来执行或简单地强制使用经典ActionResult函数中的Content-Type。

Bellow是我在MVC3中制作的一个工作案例。

控制器:

public class BookController : Controller
{
    //
    // GET: /Book/

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetAllBooks() {
        return Json(new[] { new { name = "Book1" }, new { name = "Book2" } });

    }
    public ActionResult GetAllBooksJS()
    {
        Response.ContentType = "text/javascript";

        return View();
    }
}

索引视图:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.min.js")">        </script>
    <script type="text/javascript" src="@Url.Action("GetAllBooksJS","Book")"></script>

</head>
<body>
    <div>
        <button>Get books ajax</button>        
    </div>
</body>
</html>

GetAllBooksJS查看:

@{
    Layout = null;
}

$(document).ready(function(){
    $('button').on('click',function() {
        GetBooksAjax();  
    });
});

function GetBooksAjax() {
    $.ajax({
        url: '@Url.Action("GetAllBooks","Book")',
        type: 'POST',
        dataType: 'json',
        success: function(oJSON) {
            $.each(oJSON,function(){
                alert(this.name);
            })
        }
    })
}

GetAllBooksJS查看v2,在第二个版本中,Javascript一旦被Index视图加载,就会启用Ajax Call,我想这就是你的情况:

@{
    Layout = null;
}

function GetBooksAjax() {
    $.ajax({
        url: '@Url.Action("GetAllBooks","Book")',
        type: 'POST',
        dataType: 'json',
        success: function(oJSON) {
            $.each(oJSON,function(){
                alert(this.name);
            })
        }
    })
}
GetBooksAjax();