I have such JavaScript code:
<script>
function Foo() { alert('Foo'); }
$.post('file.php', {}, function(data) {
$('#elem').append(data)开发者_如何学编程;
});
</script>
<div id="elem"></div>
Example data:
<script>Foo()</script>
Sure, Foo()
is inaccessible there. How can I grab call it?
Make sure
- jQuery is loaded
#elem
is defined when the return from the ajax call occurs. (try putting it before the script just to make sure)- Make sure the function
foo
is not defined inside the document ready method of jquery$(function(){ //FOO should not be defined in here.. });
.
example at http://jsfiddle.net/k7Y55/2/
foo
should be accesible if it was defined before you call it.
Also, you should terminate your function calls with a semicolon ;
<script>
function Foo() {
alert('Foo');
}
</script>
...
<script>
Foo();
</script>
try:
$.ajax({
url: "test.html",
dataType: "script",
success: function(data){
$('#elem').append(data);
}
});
Hope this helps.
If you append("<script>Foo()</script>")
, the /
breaks the string.
Just add the \
char, like this: append("<script>Foo()<\/script>")
.
Yes, I know that this string is an ajax return in your case.
So, just return "<script>Foo()<\/script>"
from server-side.
Take a look at this Fiddle: http://jsfiddle.net/ErickPetru/qps2q/
easy answer. you need to set a variable like so: var foo = function(){}
<script type="text/javascript">
var foo = function(data){
alert(data);
}
$.post({
url: 'someurl.aspx',
success: function(data){
foo(data);
}
});
</script>
精彩评论