代码之家  ›  专栏  ›  技术社区  ›  NVG

jquery ajax函数返回

  •  1
  • NVG  · 技术社区  · 14 年前

    我有嵌入flash的功能:

    function embedswfile(target, swf, base, width, height) {//dosomething}
    

    我想这样调用函数

    embedSwf("flashgame",decode("<?=base64_encode($path['location'])?>"),decode("<?=base64_encode($path['base_directory'])?>"),"800","600" )
    

    我的想法是,每当有人在我的网站内寻找任何SWF,他都找不到任何干净的东西。我会改变编码算法,但这只是暂时的。为了使该函数工作,每当我调用函数“decode”时,它必须返回单个值。PHP包含

    <?php
    echo base64_decode($_POST['s']);
    ?>
    

    我试过了,但还是不行

    var globvar;
    function processdata(newmsg) {
        globvar = newmsg;   
    }
    
    function decode(s){
        $.ajax({type: "POST",
            url: "includes/decode.inc.php",
            data: "s=" + s,
            success:function(newmsg){
               processdata(newmsg);
            }
        });
    return globvar;
    }
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Community pid    7 年前

    重要:

    忘记使用Ajax和编码,解码路径。你认为你从中得到了什么?安全?不可以。可以看出这是bas64编码的,或者他只是监视网络流量并从ajax调用中读取响应。

    只要做

    embedSwf("flashgame","<? =$path['location']?>"),"<?=$path['base_directory']?>","800","600" )
    

    实际上,你不能阻止其他人看到数据,只是让事情变得更复杂。

    ( 或者你必须用javascript解密数据。 )


    ( 但原始答案仍然正确 )

    Ajax是异步的,所以 var test = decode(s); 永远不会工作。解码函数将返回 之前 Ajax调用结束。

    相反,将您的逻辑放入回调处理程序。例如,如果您的代码以前是这样的:

    var retdata = decode('s');
    // here comes code that handles retdata
    

    将代码放入函数并从成功处理程序调用它:

    function process(retdata) {
        // here comes code that handles retdata
    }
    
    function decode(s){
        $.ajax({type: "POST",
            url: "includes/decode.inc.php",
            data: "s=" + s,
            success:function(newmsg){
               process(newmsg);
            }
        });
    }
    

    对于所有初学者来说,这似乎是一个非常常见的问题。在这里你会发现很多关于 same problem .

    更新:

    不太好,但您可以将函数改为

    function decode(s, cb){
        $.ajax({type: "POST",
            url: "includes/decode.inc.php",
            data: "s=" + s,
            success:function(data){
               cb(data);
            }
        });
    }
    

    并且做

    decode("<?=base64_encode($path['location'])?>", function(location) {
    
        decode("<?=base64_encode($path['base_directory'])?>", function(dir) {
    
            embedSwf("flashgame",location,dir,"800","600" );
    
        });
    
    });
    

    更新2:

    为了完整性,可以使用 async: false . 这样就可以了:

    function decode(s){
        var ret;
        $.ajax({type: "POST",
            url: "includes/decode.inc.php",
            data: "s=" + s,
            async: false,
            success:function(newmsg){
               ret = newmsg;
            }
        });
        return sync;
    }
    
    var val = decode(s);
    

    但是,在Ajax调用完成之前,这将阻塞浏览器。你必须测试在你的情况下这是否重要。

    更新3:

    您还可以将PHP脚本更改为不仅接受一个参数,还接受多个参数,并一次性处理这两个字符串。