开发者

Can't get $.proxy to work, what am I doing wrong?

开发者 https://www.devze.com 2023-04-09 10:00 出处:网络
I\'m trying to use proxy inside the jQuery UI Dialog for a $.post AJAX call, but I can\'t seem to get it to work, it\'s not running the alert box, but the post is working successfully.

I'm trying to use proxy inside the jQuery UI Dialog for a $.post AJAX call, but I can't seem to get it to work, it's not running the alert box, but the post is working successfully.

Here's were I'm at, this is the create button on the dialog.

开发者_如何学编程'Create Category' : function(){
    var newCategory = $('#new-category-name').val();
    if(newCategory != ''){
    var data = {category:newCategory, ci_csrf_token: $("input[name=ci_csrf_token]").val()};
        $.post('/create/category', data, $.proxy(this.ajaxSuccess, this),'json');
    }

    ajaxSuccess = function(data)
    {
        alert ("Here");
            // Handle Data
        $(this).dialog('close');
    }
},
'Cancel' : function(){
    $(this).dialog('close');
}

I've also tried this.ajaxSuccess = function(data) and ajaxSuccess: function(data) in the dialog initialization with no luck.

Any help would be appreciated.

I've also setup this fiddle if you need it: http://jsfiddle.net/CubedEye/CfmtJ/


If I understood correctly, you could reuse your logic to handle the data and close the dialog with something like this:

function handleData(data, dg) {
    alert(data);
    $(dg).dialog('close');
}
//$('#add-category-dialog').ajaxSuccess(function(){
//    $(this).dialog('close');
//});
$('#add-category-dialog').dialog({
    modal: true,
     buttons: {
        'Create Category' : function(){
            $.post('/', {}, function(data){             
                handleData("test",$('#add-category-dialog'))    
            });
        },
        'Cancel': function(){
            $(this).dialog('close');
        }
    },
});


You need to declare the function before using it. Also, you may want to do that with the var keyword, so the variable is not in the global scope. See this in action: http://jsfiddle.net/william/CfmtJ/5/.

You can also achieve this without using $.proxy(); you can use $.ajax() with the context option. So, the original $.post() would look like this:

        $.ajax({
            type: 'POST',
            context: this,
            data: {},
            success: ajaxSuccess
        });

See this in action: http://jsfiddle.net/william/CfmtJ/6/.

0

精彩评论

暂无评论...
验证码 换一张
取 消