将php插入js文件 [英] Inserting php into js file

查看:97
本文介绍了将php插入js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个加载gif的画廊。在我的js文件中,我有这个代码来显示加载器:

I have a loading gif for the gallery on my website. In my js file I have this code to show the loader:

image: $("<img src='images/loading.gif'/>"),

目前这个图片没有显示,因为我没有不要把完整的图像路径。但我没有放完整个图像路径,而是希望这样做:

Currently this the image isn't appearing because I haven't put the full image path. But instead of putting the full image path, I would prefer to do this:

<img src="<?php bloginfo('url');?>/images/loading.gif">

但是我无法解决如何让这个PHP在我的js文件中工作。我如何以最简单的方式去做?

But I can't work out how to make this php work in my js file. How do I go about doing it in the easiest way?

推荐答案

我更喜欢..

1)在我的标题中包含(php包含任何< head>数据),编写一个小的
内联JS函数,它创建一个包含我需要的任何变量的全局对象服务器(PHP)。我可以在这里使用'echo'和'json_encode'函数,因为它在php中的内联JS片段中文件。

1) In my header include (the php include that contains any <head> data), write a small inline JS function that creates a global object containing any variables I need from the server (PHP). I can use the 'echo' and 'json_encode' functions here because its in an inline JS snippet in a php file.

2)您可以在JS文件中编写一个JS函数,该函数使用AJAX来调用PHP文件,该文件将返回相同的文件JSON将数据编码为数字1,然后解析它并分配给全局变量。

2) You could write a JS function inside your JS file that uses AJAX to call a PHP file, which will return the same JSON encoded data as number 1, then you parse it and assign in to a global variable.

两者都是必需的你做同样的事情,除了2你使用AJAX,这将添加一个额外的请求。我更喜欢选项1,因为它与页面执行一起完成。选项2可能要求您等待DOM准备就绪,具体取决于程序的各个方面(我无法分辨)。

Both essentially do the same thing, except with 2 you are using AJAX, which will add an additional request. I prefer option 1, because it is done along with the pages execution. Option 2 may require you to wait until the DOM is ready, depending on various aspects of your program (in which I can not tell).

选项1需要内联JS,但你真的不应该对此有所了解,因为动态网站实际上可以是一个优点,因为它简洁明了。有些人对内联JS有所了解。不要让他们对你大喊大叫。

Option 1 requires inline JS, but you really shouldn't harp on this, as with dynamic websites it can actually be a plus, as along as it is short and concise. Some people get on others about inline JS. Don't let them yell at you.

这篇关于将php插入js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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