dongyuqie4322 2010-11-06 12:24
浏览 82
已采纳

如何从ajax返回调用JavaScript函数

I have a $.POST call that return the name of a function that need to be ran but it wont execute the function and I don't know why.

Here is an example:

JS file:

$(function(){
     $.post('test.php',{event: 'add'},
          function(data){
               data.func(data.msg);
          },'json');

     function test(msg){
          alert(msg);
     }
});

PHP Ajax:

<?php
     switch($_POST['event']){
          case 'add':
               $output['func'] = 'test';
               $output['msg'] = 'This is add message';
               break;
          case 'delete':
               $output['func'] = 'test';
               $output['msg'] = 'This is delete message';
               break;
     }
     echo json_encode($output);
 ?>

The problem I am having is the ajax is returning the name of the function (test) but it will not run the function, how do I fix this?

  • 写回答

2条回答 默认 最新

  • dounao1856 2010-11-06 12:33
    关注

    DO NOT USE EVAL.

    Rather, make an object with the functions you want to be executable. For example:

    var functionTable = {
        test: function (msg) {
            alert(msg);
        }
    };
    
    $.post('test.php', { event: 'add' }, function (data) {
        if (functionTable.hasOwnProperty(data.func)) {
            functionTable[data.func](data.msg);
        }
    }, 'json');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?