Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Inline jQuery script not working within AJAX call

I have a issue:
while i call a inline script (wich uses jQuery too) from another page with ajax - it seems, that jQuery is no more defined (?), and I cannot use any of jQuery functions, that should be applied (according to inline script) to content.

It's basically a news list, which holds links to particular news items. I prefer using inline-script at this time, because I won't need this functionality elsewhere.

$.ajax({
 url: href,
 cache: false,
 success: function(html){
  $('#fancy_ajax').append($(html).find('.mainContentPadded'));
}
});

As you can see, I'm simply calling a part of another page and appending its contents to page.

When I load full page (not the part of it) - jQuery works as expected (that's why I came across the idea, that it needs to be "rebinded").

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So if I understand your question correctly you have some JavaScript contained within the html variable ? If so it will not work, because JavaScript that is retrieved from an AJAX hit is not executed by the browser due to security risks.

I recommend you include the necessary javascript code in your page that is initiating the the Ajax request so that it is already available when you append the new content.

*edit...

monksp added a great link as a comment that shows how to have jQuery do exactly what you want.

Here's also some code to do the same but manually:

<html>
<head>
<title>Test JavaScript JSON</title>
</head>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.2');
</script>
<body>
<script type="text/javascript">
    $(document).ready(function() {
        $.getJSON('testjs.json', function(json){
               $(document.body).append(json.html);
               eval(json.js);
             });
    });

</script>
</body>
</html>

Here's the content of testjs.json:

{"html":"<p class="newelement">Click me</p>","js":"$(".newelement").click(function() { alert($(this).text()); });"}

And finally there are a bunch of existings plugins and other things to include javascript dynamically. I used YUI Get in the past: http://developer.yahoo.com/yui/3/get/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...