通过JQuery $ .post传递javascript函数

时间:2011-10-28 19:05:34

标签: javascript jquery ajax

基本上我要做的是使用JQuery $.post通过PHP传递回调函数。类似的东西:

function loadPage()
{
    $.post('myurl.php', { 'callbackfunc' : function (info) { alert(info); } }, 
        function(data) {
            $("#divid").html(data);
     } );
}

myurl.php创建包含表格的页面。表行有一个调用回调函数的onclick处理程序。

问题是,以这种方式传递函数通过post将其作为undefined发送,如果我将其括在引号中,那么当我尝试调用它时,我得到的错误是它不是函数。

有没有办法做我正在描述的事情?

4 个答案:

答案 0 :(得分:1)

有一种方法但通常不推荐。您可以将函数作为字符串传递,然后当您使用javascript函数接收函数时使用eval()函数。

function loadPage()
{
    $.post('myurl.php', { 'callbackfunc' : "function (info) { alert(info); }" }, 
        function(data) {
            $("#divid").html(eval(data));
     } );
}

答案 1 :(得分:0)

将其作为字符串传递(双引号中的函数体,可能使用转义字符)。

答案 2 :(得分:0)

没有办法做你所描述的,但有可能做你想做的事。 (我不知道你想要什么)

你无法将JS功能传递给服务器。你只能传递字符串。

修改: 根据你的回答,我可以告诉你,你这样做的方式不仅不好,而且危险,因为它允许XSS。

最好将click函数委托给你要插入表格的div:

function loadPage(){
    $("#divid").delegate('tr', 'click', function(evt){
      //this code is different per page, change color, alert, etc
    });
    //after the above event is delegated, you can reload the table as much as you want, without needing to rebind the above event
    $.post('myurl.php', function(data) {
        $("#divid").html(data);
    });
}

答案 3 :(得分:0)

您可以在返回表后将函数附加到表行,而不是尝试让php代码使用正确的回调创建它。

function loadPage(callbackfunc)
{
    $.post('myurl.php', {}, 
        function(data) {
            $("#divid").html(data);
            $("#divid").find("tr").each($(this).click(callbackfunc));
    } );
}