开发者

How can you dynamically load Javascript functions using Ajax?

(Rhetorical Question)

I ran into a bizarre scenario today where I wanted PHP to update how the javascript behaved on-the-fly. It was irritating, here is what I tried...

/*
 * ajax-php-javascript-function-loader.php
 *
 * this gets called by AJAX and defines or re-defines the 
 * definition of dynamicDoStuff()
 */
 <script type="text/javascript">
     function dynamicDoStuff(a,b){
          <?php
          //dynamically defined function behavior
          ?>
     }
 </script>

This did not work because when the new javascript was loaded, it's scope of the new function definition was limited to the new script tag开发者_C百科s. Scripts elsewhere on the page couldn't read it.

So here is what you have to do.

/*
 * index.html
 */
 <html>
     <head>
        <script type="text/javascript">
           var dynamicDoStuff;
        </script>
        <!-- Other Head Stuff -->
     </head>
     <body>
         <!-- the body of the site -->
     </body>
 </html>

and

/*
 * axax-php-javascript-function-loader.php
 */
 <script type="text/javascript">
     dynamicDoStuff = function(a,b){
         <?php
         //dynamically define function behavior
         ?>
     }
 </script>

by defining the name of the function in the header it becomes globally accessible so you can re-purpose it dynamically using ajax and (php or whatever)


Instead of just

function newFunctionViaAjax() { ... }

you could instead use

window['newFunctionViaAjax'] = function newFunctionViaAjax() { ... };


A better approach may be to just have your AJAX method return data, in this case, a flag indicating which behavior your the method in question should adopt.

var ajaxResponseHandler = function(jsonResponse) {
    dynamicDoStuff = jsonResponse.someFlagFromTheServer == someExpectedValue 
         ? staticDoStuffA
         : staticDoStuffB;
};

Ideally, at least in most situations, your AJAX method should just return data anyway.

Also, with this method, you can have the required alternate behavior defined in a normal JavaScript file that is already loaded by the client, instead of mixing JavaScript in with your PHP.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜