简体   繁体   中英

Can I source a php file as javascript?

I am using a WP template that allows 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM