dongqiang5541 2015-09-13 21:31
浏览 103
已采纳

执行AJAX返回的脚本

TIP: "you could simple send an json object / array from php to js, and execute every entry like "update_match('1');" using the eval() function, please stop sending js code that way"- Lucian Depold.


In the index.php, I have this code, which executes when the document is ready:

$.post('php/main.php', {elements: 1}, function(return_msg) {
    alert(return_msg);
});

The respond I get is a bunch of scripts, as expected, with the expected values. However, they do not execute! How to make them execute?

Here is the response:

<script>jsfunction(37069);</script><script>updateTextbox('');</script><script>update_match('1', '19.30 Friday 15/5', '1');</script><script>update_player('1', '1', 'recoba', 'cmf', 'teo', '0', '0');</script><script>update_player('1', '2', 'nesta', 'cb', 'tsoulou', '0', '0');</script><script>update_player('1', '3', 'raul', 'cf', 'striker', '0', '0');</script><script>update_player('1', '4', 'samuel', 'cb', 'mafia', '', '1');</script><script>update_player('1', '5', 'deisler', 'cmf', 'free_kick', '1', '');</script><script>update_player('1', '6', 'ferdinard', 'cb', 'strong', '1', '');</script><script>update_match('2', 'Match 2', '0');</script>

When I had the PHP code that produced these scripts in the bottom of the index.php, all the js functions where called correctly. Because of this question though, I had to move the code to another .php file.

  • 写回答

3条回答 默认 最新

  • dstwfcz1377 2015-09-13 21:47
    关注

    Do it this way:

    In PHP...

    $arrayOfCalls = array();
    $arrayOfCalls[]="update_match('1')";
    $arrayOfCalls[]="update_match('2')";
    
    $dummy = array();
    $dummy['calls'] =$arrayOfCalls;
    echo json_encode($dummy);
    

    And in Javascript...

    $.post('php/main.php', {elements: 1}, function(return_json) {
        return_json = JSON.parse(return_json);
        return_json.calls.forEach(function(code){
        eval(code);
        })
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?