Insert new JS method from JS
I need call from JavaScript file php like example
$.post("my.php",
function(data)
开发者_如何学JAVA{
data; // data is string "function Alert(){ alert("text"); };"
}
);
so from php I get new JS function. Like example function Alert(){ alert("text"); };
Can I insert that functionality into loaded js file? And how to do it?
If you must do this, I would advise against sending back all that text. Just send back the body:
alert("text");
Then you can do this:
$.post('my.php', function(data) {
new Function(data) ();
});
By wrapping the code up in a function you (to some extent) contain the possible weirdness that might be caused by a simple "eval()". (You could alternatively do "eval()" in its own anonymous function, but it's really hard for me to recommend using "eval()" at all on SO.)
Now, if you want to keep the function around for invocation later, then you'd do something like this:
$.post('my.php', function(data) {
window['newFunction'] = new Function(data);
});
Then you can call it as window.newFunction()
whenever you like.
Try eval
$.post("my.php", function(data)
{
eval(data); // data is string "function Alert(){ alert("text"); };"
}
);
What you want is the eval
function, which evaluates a string as JS code: http://www.w3schools.com/jsref/jsref_eval.asp
(Be careful with it, as there are obvious security concerns.)
if you know you're getting a new function from the php, you should be able to just instantiate it when you get it back:
$.post("my.php",
function(data){
data();
}
);
I would avoid eval
b/c of security issues.
Set dataType
to script to tell jQuery to evaluate it.
"script": Evaluates the response as JavaScript and returns it as plain text.
http://api.jquery.com/jQuery.ajax/
Use:
$.post("my.php", function(data){
}, 'script');
or:
$.ajax({
type: 'POST',
url: 'my.php',
success: function(data){
}
dataType: 'script'
});
Does the request need to be a POST? If not, you can use $.getScript
.
$.getScript('my.php', function(data){
});
Which is the same as:
$.ajax({
url: 'my.php',
success: function(data){
}
dataType: 'script'
});
This method uses jQuery's $.globalEval
instead of eval()
.
精彩评论