I am using this code to load and pass data to js file
jQuery.ajax({
async: true,
type: "GET",
url: "js/test.js",
data:({data : result}),
success: function() {},
dataType: 'script' });
and in the the test.js I have this
alert(result);
but alert is not working and it does no开发者_运维百科t throw any error... test.js file cannot recognize parameter passed... I know this is easy if i have a php file but what about js?
I am using firebug, result variable is defined.. Lets say i pass a string "hello" as parameter
data:{data : 'hello'},
firebug shows this : http://localhost/js/test.js?data=hello
but still alert(data);
in the test.js does not work
The general Question is: How to read a parameter passed in a js file?
Are you sure that at the moment you are calling this function the result
variable is actually defined? Try like this to see if it works. Also make sure that this variable is also defined in your test.js
when alerting it:
jQuery.ajax({
type: 'GET',
url: 'js/test.js',
data: { data : 'result' },
dataType: 'script'
});
You could also take a look at the .getScript()
function
Just do:
result = something;
jQuery.ajax({
async: true,
type: "GET",
url: "js/test.js",
success: function() {},
dataType: 'script' });
The data parameter will be serialized to a query string, which isn't what you want.
You can put the variable in a namespace if you want. An alternative is to let the external JavaScript file define a function which you then call.
As Mathew said, there is no real clean way. Here is the best I could find:
jQuery.ajax({
async: true,
type: "GET",
url: "js/test.js",
context: result,
success: function(data) { (new Function("result", data))(this.context); },
dataType: 'text' });
Whats happening here is that we getting the script as text, and evaluating it into a function with an argument "result". The effect is having a function like:
function(result) { /* contents of js/test.js */ }
And calling it by passing the value from this.context.
script.aculo.us has a module loader similar to this. It relies on a script being inserted in the last position on the head. That script then reads the SRC for the last script (itself) and parses everything after the '?'.
The downside to this approach is the browser locks up while the file is downloading and parsing (AKA, not async). If you have the ability to parse the JS file though a server side language (PHP, Perl, etc), then you'll be much better off.
As a side note. Most apache configs don't allow you to "POST" to a js file. It will return a strange error (501 I think?), so watch out for that.
精彩评论