繁体   English   中英

如何从ajax返回调用JavaScript函数

[英]How to call JavaScript function from ajax return

我有一个$ .POST调用,该调用返回需要运行的函数的名称,但它不会执行该函数,我也不知道为什么。

这是一个例子:

JS档案:

$(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);
 ?>

我遇到的问题是ajax返回了函数的名称(测试),但无法运行该函数,如何解决此问题?

请勿使用评估。

而是使对象具有您希望可执行的功能。 例如:

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');

我认为最好将函数移到此处的对象中,以便可以查看它是否存在:

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');
      });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM