如果在浏览器中禁用了JavaScript,那么ajax请求是否有效?

Nul*_*ter 7 javascript jquery asp.net-mvc-3

我正在开发一个Web应用程序,并使用jQuery为用户提供良好的用户界面.因此,我使用的是ajax请求和许多jQuery函数.

如果我在浏览器中禁用JavaScript,大部分功能将无法工作,因为我正在为许多功能发送异步ajax请求.但是我该如何处理呢?我是否需要在不使用jQuery和ajax的情况下重写代码?

在下面找到一个示例按钮单击事件:

  $("#renameCategory").live('click', function (event) {
         if ($.trim($("#CategoryNewName").val()) == "") {
             alert("Please enter a category name");
             return;
         }
         var selectedCategory = $("#SelectedCategoryId").val();
         var newCategoryName = $("#CategoryNewName").val();
         var postData = { categoryId: selectedCategory, name: newCategoryName };
         $.ajax({
             type: "POST",
             url: '@Url.Action("UpdateCategoryName", "Category")',
             data: postData,
             dataType: "json",
             success: function (data) {
                 $('#' + selectedCategory).text(newCategoryName);
                 $("#selectedCategoryText").html(newCategoryName);
             },
             error: function () { alert('error') }
         });
     });
Run Code Online (Sandbox Code Playgroud)

我怎么处理这个?

Pau*_*aul 13

当客户端禁用JavaScript时,Ajax请求和jQuery将无法运行.使这项工作的最佳方法是使用<a>标记href中的URL,如下所示:

<a href="@Url.Action("UpdateCategoryName", "Category")">Click Me!</a>

$("#renameCategory").on('click', function (evt) {
        //To prevent the link from sending the default request
        //call preventDefault() on the jQuery event object
        evt.preventDefault();
        //
        if ($.trim($("#CategoryNewName").val()) == "") {
             alert("Please enter a category name");
             return;
         }
         //GET THE URL FOR THE AJAX REQUEST
         var actionUrl = $(this).attr('href');
         //
         var selectedCategory = $("#SelectedCategoryId").val();
         var newCategoryName = $("#CategoryNewName").val();
         var postData = { categoryId: selectedCategory, name: newCategoryName };
         $.ajax({
             type: "POST",
             url: actionUrl,
             data: postData,
             dataType: "json",
             success: function (data) {
                 $('#' + selectedCategory).text(newCategoryName);
                 $("#selectedCategoryText").html(newCategoryName);
             },
             error: function () { alert('error') }
         });
     });
Run Code Online (Sandbox Code Playgroud)

您还需要在Controller中检查ajax请求,如下所示:

public ActionResult UpdateCategoryName() {
    ...

    if(Request.IsAjaxRequest()) {
        return Json(yourData);
    }

    return View();
}
Run Code Online (Sandbox Code Playgroud)

这样,如果您的用户禁用了JavaScript,该链接将像普通的HTTP请求一样运行.如果用户启用了JavaScript,那么他们将获得Ajax体验.这叫做graceful degradation.