开发者

Problem in jQuery and XmlHttpRequest

I am trying to call a PHP page with XmlHttpRequest (AJAX). My problem is that I have jQuery (javascript) included in my PHP page like this:

<script language="javascript" src="jquery.js"></script>
<script language="javascript">
   // my jquery code here
</script>

When I call the开发者_JAVA技巧 PHP page with XmlHttpRequest it fails! That is, the response only shows the PHP content but jQuery is not working! When I access that PHP page directly it works.

So, how can I fix this problem?


You probably have your jquery code like this:

$(document).ready(
      function() { //something magic }
);

The fact is: it won't fire if you load it through AJAX.

To run it, you simply have to remove the $(document).ready part.

You might also read a discussion about it.


Javascript cannot be loaded via a xmlHttpRequest call as the javascript is registered during the page load, you need to load all javascript during the initial load


Your ajax calls should invoke a php file that only outputs json. Then your ajax success handler can use that json to run whatever javascript you need

--ajax.php -- no JS or jQuery allowed here, just echo json
<?php
echo json_encode(array('message'=> 'Ajax is fun'));
?>

--page.html
$.get('ajax.php', function(data) {
  console.log('Ajax call returned', data.message);
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜