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条)

报告相同问题?

悬赏问题

  • ¥15 overleaf中论文编辑,报错`pages' is a missing field, not a string, for entry 4
  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么