Ajax调用不加载页面但是进入.fail?

时间:2015-05-04 09:23:02

标签: jquery asp.net-mvc

这是我目前正在处理的MVC应用程序。 因此,我们会在其中显示产品详细信息的页面。 在此页面上有一个链接点击,该链接会加载另一个页面,其中显示了一组处理此产品的规则。

以下是我现在尝试的内容:

控制器,现在做的不多:

public class ProductRuleController : Controller
{
    [HttpGet]
    public ActionResult GetAllRulesForProduct(string productId)
    {
        return View("AddEditProductRule");
    }
}

观点:

@{
    ViewBag.Title = "Add / Edit Product Rule";
}
<h2>Add / Edit Rule</h2>

JS

function ShowProductRules() {
var urlToGetProductRules = "/ProductRule/GetAllRulesForProduct/";
var productId = $('#ProductId').val();

if (productId == null) {
    alert('Please Check the ProductId');
}
else {
    // Make an ajax call passing in the ProductId
    alert('ProductId: ' + productId);
    $.ajax({
        type: "Get",
        url: urlToGetProductRules,
        data: { productId: productId },
        dataType: "json"
    })
        .done(function (data) {

        })
        .fail(function (xhr) {
            alert("Something went wrong!!!")
            console.log(xhr.responseText);
        });
}

ajax调用进入.fail部分。我检查了responseText,其中包含了所需的HTML而没有任何错误。

所以我的问题是,当响应中包含所需的HTML时,为什么它会转到Fail部分? 我做错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

从ajax调用中删除dataType: "json"部分

$.ajax({
        type: "Get",
        url: urlToGetProductRules,
        data: { productId: productId },
    })
        .done(function (data) {

        })
        .fail(function (xhr) {
            alert("Something went wrong!!!")
            console.log(xhr.responseText);
        });

当你指定dataType : "json"时,ajax调用会产生json响应。如果是html,它会将其视为错误,因此失败部分将执行。如果你仍想使用dataType : "json" ,然后将响应转换为json格式。