dongyuqie4322
2010-11-06 12:24
浏览 81

如何从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');
    
    已采纳该答案
    打赏 评论
  • druhoytza979667566 2010-11-06 12:34

    I think it's better to move your function into an object here, so you can see if it exists or not:

    var possibleFunctions = {
      test: function(val){
        alert(val);
      }
    };
    
    $(function(){
         $.post('test.php',{event: 'add'},
              function(data){
                  if(possibleFunctions[data.func]){
                      possibleFunctions[data.func](data.msg);
                  }
              },'json');
          });
    });
    
    打赏 评论

相关推荐 更多相似问题