Javascript string variable that contains PHP code
I basically just wan开发者_Go百科t to append a javascript variable to an HTML div with JQuery. However I need to append some PHP code as a string, it doesn't need to execute it just needs to show up as a plain old string string.
The following code doesn't seem to append because I think it is still recognized as PHP syntax.
var script = '<?php wp_list_pages(); ?>';
divName.innerHTML = script;
Any help would be much appreciated.
Just a guess... replace the php brackets with HTML entities (< and >) so it will not be interpreted as PHP code (if you run the file containing the JS through PHP) nor as strange HTML code (the browser searches for brackets as html tags, remember...) by the browser.
Wrap it in CODE
tags, like this:
var script = '<code><?php wp_list_pages(); ?></code>';
Try:
var script = '<?php echo '<?php wp_list_pages(); ?>'; ?>';
You probably should escape the "hot" HTML tokens in the PHP text:
div.innerHTML = script.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
You need to simply escape the string with HTML entities (< and >)
IMPORTANT: I hope all you're doing here is trying to display the PHP code. Please don't try anything funky where PHP code is passed in a form's field back to the server and executed via eval()
or somesuch. That would be an unimaginably terrible idea. Anytime you give the client access to code that will be executed on the server, you open yourself up to all kinds of exploits. Your server will be forfeit. Do not collect $200. Game over. Fail.
PHP is executed before the page is sent to the browser, so you can go to that page, open its source and see if in that line you see what you need to see, like:
var script = 'the content you expect to see';
if not, tell us what you see.
If you are looking for a String variable to execute PHP code try looking here instead. I mention this because this was what I was looking to do and this question came up.
精彩评论