jQuery Ajax Issue - 仅在结果返回时执行的函数

时间:2012-11-08 08:06:59

标签: javascript ajax jquery

下面是我对控制器进行的jquery ajax调用

jQuery.post('index.php',{
                'option'    : 'com_test',
                'controller': 'product',
                'task'      : 'loadColors',
                'format'    : 'raw',            
                'design_id' : design_id,
                    'collar_id' : collar_id                        
        },function(result){            
        }).success(function(result) { 
                alert(result); 
            }).error(function() { 
                jQuery('div#color_wrapper h1').text('ERROR WHILE LOADING COLORS');
            }).complete(function(result) { 
                alert(result); 
            });

在我的控制器中有如下功能。

function loadColors()
    {
        die;
    }

我的问题是,即使我在loadColors()中使用了die,也正在执行成功和完整的功能。我想要的是一个函数,如果我们从loadColors()返回一些东西,它会运行吗?我怎么能完成它?

4 个答案:

答案 0 :(得分:2)

执行.success()时,$.post是不必要的,因为function(results)仅在帖子返回成功时被调用。

jQuery.post('index.php',{
               'option'    : 'com_test',
               'controller': 'product',
               'task'      : 'loadColors',
              'format'    : 'raw',            
               'design_id' : design_id,
                  'collar_id' : collar_id                        
       },function(result){            

          alert(result);
       });

是你想玩的东西。

答案 1 :(得分:1)

我个人只会检查回调是什么,然后决定你想做什么。

.success(function(result) { 
    if (result == "") {
        alert("empty result!");
    } else {
        alert("non empty result! " + result);
    }
})

例如。

如果你真的不想通过PHP脚本运行成功函数,你应该检查其他标题,以便在你死之前回复。我不完全确定这是否有效,因为我之前没有使用它,但你可以发送标题告诉页面上有错误。

答案 2 :(得分:1)

调用函数success和complete是因为调用中没有出错。你什么都不回报。如果调用它自己出错的东西(即超时或状态代码!= 200),则调用错误函数。

您必须检查成功功能。

...
success(function (result) {
    if (!result) {
        alert('Error');
        return;
    }

    // do the right stuff

})

答案 3 :(得分:1)

如果要在客户端代码中触发error处理程序,则应该使用错误代码404 Page not found500 Internal server error等返回查询...。< / p>

在服务器端使用php,您可以使用header功能:

function loadColors()
{
    header('HTTP/1.1 500 Internal Server Error');
    die;
}