如何使用 Javascript 和 PHP 创建可嵌入的小工具?
我正在使用 Javascript 和 PHP 进行编程。我创建了一个简单的网站,允许填写测验并获得结果。现在我想让用户有机会将此测验嵌入到他们的网站上。如何做到这一点?它应该以类似 Google Gadgets、Adsense 之类的类似方式工作:这样,当有人将我的 html 代码(带有 JS?)放到他们的网站上时,测验就会在他们的网站上显示和运行。
您知道有关执行此类操作的任何教程或对我如何开始搜索和学习它的提示吗?
I'm programming in Javascript and PHP. I've created a simple website that allows to fill in a quizz and get result. Now I would like to give users opportunity to embed this quizz on their website. How to do this? It should work in some near manner like Google Gadgets, Adsense and that: that so when someone will put my html code (with JS?) on their websites, quizz will display and work on their site.
Do you know any tutorials about doing such things or tips for me how to start searching and learning about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法,也是最好的性能和安全性方法,是使用
。只需创建页面的小版本即可嵌入。
是同步加载的并可以访问站点的 cookie,因此这不是一个好的嵌入解决方案。
如果您只是要求用户将
嵌入到他们想要小工具的位置,您就可以使用
document.write
生成标记(简单,仅适用于 HTML)。更好的方法是要求用户从脚本中调用函数,将代码插入到选定的 DOM 节点中(使用 W3C DOM)。这允许更聪明的网站管理员异步加载脚本。 SWFObject 就是这样设计的。
The easiest way, which is also best performance- and security-wise, is to use
<iframe>
. Just create small version of your page for embedding.<script>
is loaded synchronously and gets access to site's cookies, so it's not a good solution for embedding.If you just ask your users to embed
<script>
in place where they want the gadget to be, you'll be able to generate markup withdocument.write
(easy, works in HTML only).A better way is to ask users to invoke function from your script that inserts code into selected DOM node (using W3C DOM). This allows smarter webmasters to load script asynchronously. SWFObject is designed like that.
如果您需要使用 PHP,您可以告诉您的服务器将 .js 文件解析为 PHP:
在
quiz.js
文件中,使用 PHP 代码从数据库或其他内容中检索问题。然后,将 mime-type headers 设置为 Javascript 并输出 Javascript 代码。尽管正如porneL所说,使用iframe更简单。这就是 Google 小工具的作用。
If you need to use PHP you could tell your server to parse a .js file as PHP:
In the
quiz.js
file, use PHP code to retrieve questions from a database or whatever. Then, set mime-type headers to Javascript and output Javascript code.Though as porneL says, using an iframe is simpler. That's what Google Gadgets does.