如何在jQuery的$ ajax方法的成功函数中执行javascript代码?

时间:2013-10-13 12:42:45

标签: javascript php ajax jquery

我正在使用以下代码段。我已将评论放在未执行的代码之前。

$(document).on('click', '#disable_url', function (e) {    
    e.preventDefault();

    var items = new Array();

    $("input:checked:not(#ckbCheckAll)").each(function() {
      items.push($(this).val());
    });

    var str = $("#user_filter").serialize();    
    var str = decodeURIComponent(str);

    var user_status = new Array();
    for (var i = 0; i < items.length; i++) {
      //user_status.push($("#"+items[i]).val());
      user_status.push($("#"+items[i]).val().replace(/'/g,''));
    }      

    $.ajax({
      type: "POST",
      url: "manage_users.php?op=disable_bulk_users&items="+items+"&options="+str+"&user_status="+user_status,
      dataType: 'json',  
      success: function(data) {
        var redirect_link = data.href;
        window.location.href = redirect_link;
      }          
    });
/*The below code is not getting executed. It is expected to be executed upon the success response from PHP file otherwise not*/
    for (var i = 0; i < items.length; i++) { alert("Nibble");
      var status = 'enable'; 
      id = items[i];
      $('#user_status_'+id).html('<img src="{/literal}{$control_img_url}{literal}disable.png" border="0" alt="Enable User" width="20" height="20" />');
      $('#user_status_'+id).attr('title','Enable User');
      $('#user_status_'+id).attr('onClick', "change_user_status('"+module_url+"', '"+op+"', '"+id+"', '"+status+"');return false;");
    }
/*The non calling code ends here*/ 
      })

从请求到成功响应和页面重定向的一切工作正常但我无法在从PHP文件接收成功响应时执行代码。如果未收到成功响应,则不应执行此代码。你能帮我这方面吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

你有这个部分:

  success: function(data) {
    var redirect_link = data.href;
    window.location.href = redirect_link;
  } 

当然,这是成功的callback。请求完成后,您的浏览器收到成功响应,该函数将被执行。如果你想在回调中执行任何其他操作,只需将代码写入函数。

此外,如果您重定向浏览器,那么不要指望您的HTML会被明显更改,因为您不会看到任何更改,因为重定向是 instant 。使用setTimeout功能延迟重定向。