开发者

How to call JavaScript function from ajax return

开发者 https://www.devze.com 2023-01-23 15:03 出处:网络
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.

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 i开发者_JAVA百科s returning the name of the function (test) but it will not run the function, how do I fix this?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消