有没有办法将OnSuccess脚本添加到我的Ajax调用中

时间:2014-05-22 23:46:27

标签: javascript jquery razor

我有以下脚本:

$.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
        OnSuccess('createsuccess')         
    },
});

我想要做的是在显示对话框后触发OnSuccess脚本,目前我收到一个未定义OnSuccess的异常?那么有人可以建议如何为我的Ajax调用激活OnSuccess脚本吗?

2 个答案:

答案 0 :(得分:1)

使用jQuery.when()所述的in this answer here尝试此操作:

  

提供一种基于一个或多个执行回调函数的方法   对象,通常是表示异步事件的延迟对象。

因此,考虑到这一点,以下是您使用jQuery.when()重新编写的代码:

var ajax_action = $.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
    },
});

$.when(ajax_action).then(function(data, textStatus, jqXHR) { OnSuccess('createsuccess'); });

或者,如果您只想测试此概念,请将jQuery.when()更改为:

$.when(ajax_action).then(function(data, textStatus, jqXHR) { alert('I am a success!'); });

编辑:上次修改以尝试解决原始海报请求。他们想要触发一个名为createsuccess的脚本,所以就这样做:

$.when(ajax_action).then(function(data, textStatus, jqXHR) { createsuccess(); });

答案 1 :(得分:1)

如果你添加一个,你的代码应该可以工作;在你的OnSuccess电话之后。这不是一个要被触发的事件,但它是一个将在前两个语句之后执行的函数。

function OnSuccess(p_Success) {
    alert('it worked!');
}


$.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
        OnSuccess('createsuccess');
    },
});