开发者

Can I source a php file as javascript?

开发者 https://www.devze.com 2023-03-06 11:38 出处:网络
I am using a WP template that allows 开发者_Go百科me to incorporate arbitrary HTML.Unfortunately, I have to use this particular widget and can\'t use other WP widgets.

I am using a WP template that allows 开发者_Go百科me to incorporate arbitrary HTML. Unfortunately, I have to use this particular widget and can't use other WP widgets.

I have on my webserver /some/path/serve_image.php that spits out a random HREF'd IMG SRC with a caption and some other info from a MySQL query.

Now...how can I say "take that output and treat it as HTML"? If I just put "/some/path/serve_image.php" I get that literal string.

I tried:

<script type="javascript" src="/some/path/serve_image.php"></script>

but that didn't work. I tried changing everything in serve_image.php to be document.write() calls and that didn't seem to work either. I'm not the world's greatest JS guy...

So if I have a URL on the net that spits out some HTML and I want to include that HTML in my web page, what's the best way to do that? Sort of like what Google does with Adsense - you source their show_ads.js.


Why no? Add

header('Content-Type: application/javascript');

And output JavaScript Like:

echo("var image = \"".$images[array_rand($images)]."\";");
echo("$('img.randim').attr('src', image);


No. JavaScript and PHP are two completely separate languages. In fact, if it was JavaScript, you aren't even loading it the right way.

<script type="text/javascript"></script>

The way you're trying to do it would throw a parse error, because it would try to use the PHP as JavaScript. Some browsers would even reject it, because PHP files have a text/html MIME type, while JavaScript should be application/javascript.

PHP has to be done server side, so loading it in the client just doesn't work.

What I think you're after is this:

<?php

    require('/some/path/serve_image.php');

?>

Just place that wherever you want the image to be.

0

精彩评论

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