Ajax调用不会进入成功处理程序

时间:2015-07-09 11:15:05

标签: jquery ajax

这是我坚持的场景:

我有什么

返回Json的MVC ActionResult:

public ActionResult GetUpdates(string productId)
{
    var updatesForProduct = _repository.GetUpdates(productId);

    if (updatesForProduct.Count != 0)
    {
        return Json(
                     new
                     {
                         UpdatedData = updatesForProduct.Select(x => new[] 
                        { 
                           x.UpdatedDate.ToString(),
                           x.NewLabel
                        })
                     }, JsonRequestBehavior.AllowGet);
    }

    return Json(new { success = true });
}

JS部分:

function GetProductUpdate() {

    var urlToGetProductUpdate = "/Products/GetUpdates/"

    var request = $.ajax({
        async: false,
        url: urlToGetProductUpdate,
        method: "GET",
        data: { productId: productId},
        dataType: "JSON"
    });

    request.done(function (result) {
        if (result.success) {
            console.log(result);
        }
        else {
            alert("Not able to get Updates!");
        }

    });

    request.fail(function (jqXHR, textStatus) {
        console.log(textStatus);
        alert("Request failed.");
    });
}

发生了什么:

我可以在调试器中看到对存储库的调用返回更新列表,而在JS中它确实会进入.done承诺但是在它内部它会转到警报部分而不是成功,因为我希望它是

我做错了什么?

提前致谢。

3 个答案:

答案 0 :(得分:0)

试试这个:

request.success(function (result) {
    console.log(result.success);        
});

答案 1 :(得分:0)

当更新发生时,您不会在JSON中返回成功属性,只有在您不更新任何内容时。 如果您在完成的开头放置了console.log(结果):

request.success(function (result) {
   console.log(result);
   if (result.success) {
        console.log(result);
   }
   else {
       alert("Not able to get Updates!");
   }
});

不应找到success属性,只发送您作为JSON发送的结果:

  

{UpdatedData:[{UpdatedDate:" ...",NewLabel:" ..." }]}

您的JSON结果中可能应该有一个属性,因此您的控制器操作看起来像这样:

public ActionResult GetUpdates(string productId)
{
    var updatesForProduct = _repository.GetUpdates(productId);

    if (updatesForProduct.Count > 0)
    {
        return Json(new { success = true, updatedData = 
            updatesForProduct.Select(x => new[] 
                { 
                    x.UpdatedDate.ToString(),
                    x.NewLabel
                })
             }, JsonRequestBehavior.AllowGet);
    }

    return Json(new { success = false }); //not sure if this should be true or false in your case
}

<强>旁注:

你应该删除

async: false,

因为你正在使用延期。

答案 2 :(得分:-2)

在ajax定义中定义成功和失败的功能:

var request = $.ajax({
    async: false,
    url: urlToGetProductUpdate,
    method: "GET",
    data: { productId: productId},
    dataType: "JSON",
    success: function (data, status, jqxhr)
    {
        \\logging
    },
    error: function (jqxhr, status, errotMsg)
    {
        \\ alert
    }
});