我有如下JavaScript代码:
<script>
function Foo() { alert('Foo'); }
$.post('file.php', {}, function(data) {
$('#elem').append(data);
});
</script>
<div id="elem"></div>
示例data:
<script>Foo()</script>
当然,foo()那里是不可访问的。我怎么才能抓到它呢?
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>
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>
Make sure
#elem
is defined when the return from the ajax call occurs. (try putting it before the script just to make sure)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/
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/