0

我有一个 jQuery AJAX 调用,我需要多次调用,所以我想把它变成一个函数,但不知道怎么做。这是代码。有任何想法吗?我知道这似乎微不足道,但我环顾四周,不知道如何正确地做到这一点......

//This does the ajax call to show the actual creative
    $('#creative').change(function() {
        $.ajax({
            url: '/app/components/MailingsReport.cfc',
            //POST method is used
            type: "POST",
            //pass the data 
            data: {
                method: "getCreativeHTML",
                creativeID: $('#creative').val(),
                datasource: "shopping_cart"
                 },
            dataType: "html",
            //contentType: "application/text; charset=utf-8",
            success: function(response){
                var obj = $.trim(response);
                //alert("response");
                if (obj == '"0 records"') {
                    $('#preview').html("No creative found.");
                }
                else { 
                    $('#htmlCode').val( obj );
                    $('#preview').html( obj );
                }
            }
        })
        //if there was an error, when user clicks into field hightlight-error is removed
        $('#htmlCode').change(function(){
            $('#reloadContent').show();
        });
    });
4

2 回答 2

3
function foo(e) {
        $.ajax({
            url: '/app/components/MailingsReport.cfc',
            //POST method is used
            type: "POST",
            //pass the data 
            data: {
                method: "getCreativeHTML",
                creativeID: $('#creative').val(),
                datasource: "shopping_cart"
                 },
            dataType: "html",
            //contentType: "application/text; charset=utf-8",
            success: function(response){
                var obj = $.trim(response);
                //alert("response");
                if (obj == '"0 records"') {
                    $('#preview').html("No creative found.");
                }
                else { 
                    $('#htmlCode').val( obj );
                    $('#preview').html( obj );
                }
            }
        });
}

和电话:

$('#creative').change(function(e) { return foo(e); });
于 2012-06-25T22:58:19.817 回答
0
$.ajax({
     //parameres
    });

其实就是一个简单的函数调用,

$.ajax(parameters);

你可以将它包装在一个函数中,就像任何类似的函数调用一样:

add(1,2);

如果您在 AJAX 调用参数中使用了一些变量,例如:myUrl,那么请确保它在您调用该函数的范围内可用。

一个简单的例子:

function sendRquest(myUrl){ 
$.ajax({
    url : myUrl,
    //other parameters
    });
}
于 2012-06-25T23:07:07.823 回答