Ajax呼唤成功和失败

时间:2013-05-10 13:49:01

标签: jquery ajax

好的,所以这很奇怪。我的Ajax调用似乎同时调用成功和失败。当我发送我的Ajax调用时,它将发布到数据库,但随后也会抛出错误消息。因此Ajax调用正在运行 - 只是出现错误消息。当我用Fiddler检查问题时,请求发布为200(成功)。

代码非常简单:

var myDataObject = new Object();
myDataObject.one = $('#SomeTextBoxId').val;
myDataObject.two = $('#SomeOtherTextBoxId').val          

// NOTE: AJAX is calling success and fail
SendAjax("/ServiceHandlers/SomeHandler?HandlerName", myDataObject, function() { alert("SUCCESS!");}, function() {alert("FAILURE?");});

以下是SendAjax功能:

function SendAjax(postUrl, postData, successFunction, failureFunction)
{
  /*
     postUrl:           The URL to which the request will be posted
     postData:          The JSON encoded input to be posted to the postUrl
     successFunction:   The function to be executed on a successful post
     failureFunction:   The function to be executed on a failed post
   */

// Stringify the postData
postData = JSON.stringify(postData);

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: postUrl,
    data: postData,
    success: function (data, status, xhr)
    {
        successFunction(data, status, xhr);
    },
    error: function (xhr, status, error)
    {
        failureFunction(xhr, status, error);
    }
});
}

有什么建议吗?

编辑 - 修正了Ajax调用中的功能,但仍然没有运气。

2 个答案:

答案 0 :(得分:1)

事情就是你发送函数的方式,因为参数错误。

当您“发送”alert("SUCCESS!")作为参数时,您不是在发送它,而是在调用它。

相反,您需要在旅途中创建容器功能。就像这样:

// You can make it a single line if you want,
// I'm was just trying to separate it to look more clear
SendAjax(
    "/ServiceHandlers/SomeHandler?HandlerName",
    myDataObject, 
    function() { alert("SUCCESS!") },
    function() { alert("FAILURE?") }
);

答案 1 :(得分:0)

您正在拨打警报。你没有通过引用传递它们。它应该看起来像

SendAjax("/ServiceHandlers/SomeHandler?HandlerName", myDataObject, 
    function() {
      alert("SUCCESS!") 
    },
    function() { 
      alert("FAILURE?") 
    });

它试图传递警报的返回值。而不是实际的功能本身。