开发者

How to access function

开发者 https://www.devze.com 2023-03-02 11:48 出处:网络
I have such JavaScript code: <script> function Foo() { alert(\'Foo\'); } $.post(\'file.php\', {}, function(data) {

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

  1. jQuery is loaded
  2. #elem is defined when the return from the ajax call occurs. (try putting it before the script just to make sure)
  3. 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号