将jQuery AJAX调用转换为函数

时间:2012-06-25 22:53:57

标签: jquery ajax

我有一个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();
        });
    });

2 个答案:

答案 0 :(得分: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); });

答案 1 :(得分:0)

$.ajax({
     //parameres
    });

实际上是一个简单的函数调用,

$.ajax(parameters);

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

add(1,2);

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

一个简单的例子:

function sendRquest(myUrl){ 
$.ajax({
    url : myUrl,
    //other parameters
    });
}
相关问题