动态加载外部JS并将响应写入div [英] dynamically load external JS and write response to a div

查看:84
本文介绍了动态加载外部JS并将响应写入div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中嵌入了美味的Feed。当我在div中添加脚本标签时,它显然会在我的其余JS之前加载(在页面底部)。在加载了所有其他j之后,我想动态地将这个脚本加载到指定的div中。

I'm embedding a delicious feed into my page. When I just add the script tags inside the div it obviously loads before the rest of my JS (at the bottom of the page). I'd like to load this script into the specified div dynamically after all other js has loaded.

我已经尝试了getscript函数,但它确实打破了页面我用.html():

I've tried the getscript function, but it definitely breaks the page when I use it with .html():

$('#delicious').html(function(){
$.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd"); 
});

我似乎无法理解如何将该文件的结果打印到#delicious div。

I can't seem to wrap my head around how I can print the results of that file into the #delicious div.

推荐答案

如果你想在div中显示脚本,不应该是这样的,利用回调功能?

If you want to display the script in the div, shouldn't it be something like this, making use of the callback function?

$.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd", 
             function(data){
                $('#delicious').html(data);
            }); 

$。getScript()的结果是 XMLHTTPRequest 对象,而您似乎想要响应文本。

The result of $.getScript() is the XMLHTTPRequest object and it seems like you want the response text instead.

此外,它看起来像响应从您提供的URL尝试将脚本写入文档,从而覆盖您的所有页面内容。这是您的问题,您可以考虑使用 iframe 并将此网址设置为源。

Also, it looks like the response from the URL you've given attempts to write the script into the document, thus overwriting all your page content. It that is your problem you might consider using an iframe and setting this URL as it's source.

我也似乎根据脚本是跨域加载还是从同一个域加载来获取不同的行为 - 我不太清楚该怎么做,因为 getScript()是应该跨域工作。

I also seem to get different behaviour depending on whether the script is being loaded cross-domain or from the same domain - I'm not quite sure what to make of that since getScript() is supposed to work cross-domain.

这篇关于动态加载外部JS并将响应写入div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆