-
Nov 22nd, 2014, 02:08 PM
#1
What to load new JS with AJAX calls
I want to load new JS functions with AJAX calls.
If the FUNCTION that I'm looking to load is already defined, how do I get it to be replaced? If it's not already defined, how do I get it to be newly created?
-
Nov 23rd, 2014, 06:46 PM
#2
Re: What to load new JS with AJAX calls
Creating a new function via Ajax:
There's a couple of ways to do it, one safer than the other. Ajax just sends a JSON string, and you obviously can't send a function directly over JSON.
Firstly, you can put the function code into a string, send that string via JSON, and then eval() the json on the client side. This can have huge security implications, so use with extreme caution.
The other (and my preferred) way is to just include multiple functions in the js source and call each function as required. You might send some flags down through the Ajax call to determine which function to call in js.
Modifying an existing function:
You can use duck punching to modify an existing function. Paul Irish explains it nicely.
Redefining a function:
You can just define a new function with the same name as the existing function.
JavaScript Code:
// define xxxx function xxxx() { console.log("1"); } // redefine xxxx function xxxx() { console.log("2"); }
JavaScript Code:
// define xxxx var xxxx = function() { console.log("1"); }; // redefine xxxx xxxx = function() { console.log("2"); };
Last edited by tr333; Nov 23rd, 2014 at 06:52 PM.
-
Dec 8th, 2014, 10:29 PM
#3
Re: What to load new JS with AJAX calls
Lots of ways.
I load source files, and inject them into the HEAD element of the page:
Code:
var script = document.createElement('script');
script.src = uri;
script.async = false;
document.head.appendChild(script);
If you have a collection of functions which changes quite often, just maintain it in a dictionary:
Code:
szlamany.funcs = {}
szlamany.funcs.foo = function(x) { ... } // add/replace a function
szlamany.funcs.foo() // call a function
szlamany.funcs[x]() // call a function by name
This works for ordinarily defined functions as well, since at some level everything in JavaScript is a member of a dictionary:
Code:
function foo() { return 'foo' };
window.foo = function new_foo() { return 'new foo' };
> foo() // returns 'new foo'
I agree with tr333... don't use eval
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|