$ .Ajax的Succes方法在ASP MVC中不起作用

时间:2016-12-30 12:03:15

标签: javascript ajax asp.net-mvc model-view-controller

我几乎阅读了有关该主题的所有帖子。但不幸的是我无法处理我的问题。至少对我来说问题真的很尴尬: 我有一个简单的C#代码来检索ShoppingController类中提交因子的跟踪状态,如下所示:

  public string StatusOfFactor( string guid )
    {
        // note that guid was being trimmed in javascript

        Factor factor = (from Factor fact in db.Factors
                         where fact.TrackingCode.ToString() == guid
                         select fact).First();
        return factor.StatusOfFactor;

我有一个javascript函数调用此方法如下:

function TrackPurchase() {
    var txtTrackingPurchase = $("#inputpeygiry");
    var guid = $.trim(txtTrackingPurchase.val());
    var urlMain = 'ShoppingController/StatusOfFactor';
    alert(urlMain);

    $.ajax({
        type: 'GET',
        url: urlMain,
        cache: false,
        data:  guid,
        success: function (returnVal) { 
            alert("I am sucess function");
            $("#StatusOfFactor").html(returnVal);

        },
        error: function (e) {
            $("#StatusOfFactor").text("nothing is really exist");
        }
    });    
}

请注意,我有一个id="inputpeygiry"的文本框,可以接收用户的跟踪代码。通过点击下面的按钮调用上面的javascript函数:

  <input type="button" class="btn btn-success pull-left" id="btnpeygiry" value="Track Purchase" onclick="TrackPurchase()"/>

所以问题是成功功能从不打电话!!! 你能帮我解决一下吗?

2 个答案:

答案 0 :(得分:0)

您使用的是哪个版本的jQuery?从jQuery 3.0开始,删除了回调方法。您可以改为使用jqXHR.done()jqXHR.fail()jqXHR.always()

请参阅jQuery Get

的文档
$.ajax({
    type: 'GET',
    url: urlMain,
    cache: false,
    data:  guid,
})
.done(function (returnVal) { 
    alert("I am sucess function");
    $("#StatusOfFactor").html(returnVal);

}).
fail(function (e) {
    $("#StatusOfFactor").text("nothing is really exist");
});

答案 1 :(得分:0)

GET更改为POST,它应该可以正常使用。

控制器代码变为:

[HttpPost]
public string StatusOfFactor( string guid )
{
    // note that guid was being trimmed in javascript
    Factor factor = (from Factor fact in db.Factors
                     where fact.TrackingCode.ToString() == guid
                     select fact).First();
    return factor.StatusOfFactor;
}

Javascript代码变为:

function TrackPurchase() {
var txtTrackingPurchase = $("#inputpeygiry");
var guid = $.trim(txtTrackingPurchase.val());
var urlMain = 'ShoppingController/StatusOfFactor';
alert(urlMain);
    $.ajax({
        type: 'POST',
        url: urlMain,
        cache: false,
        data:  guid,
        success: function (returnVal) { 
            alert("I am sucess function");
            $("#StatusOfFactor").html(returnVal);

        },
        error: function (e) {
            $("#StatusOfFactor").text("nothing is really exist");
        }
    });
}