How to insert PHP into jQuery?

2019-03-03 02:23发布

问题:

I understand that one can't execute PHP from the client side (JavaScript), but what would then be the appropriate approach? Writing my jQuery in PHP? Here is an example of what I'm looking for.

<!-- Wordpress template URL -->
<div id="template_directory" style="display: none;">
    <?php bloginfo('template_url'); ?>
</div>

<!-- Fetch with jQuery -->
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="' + templDirec + '/images/my-image.jpg" />';

Since I'm new to this, simple descriptive answers are preferred. What's the best way of having js and php work together? Thanks

回答1:

First, you should wrap js-code with script-tag:

<!-- Wordpress template URL -->
<div id="template_directory" style="display: none;">
    <?php bloginfo('template_url'); ?>
</div>

<!-- Fetch with jQuery -->
<script type="text/javascript">
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="' + templDirec + '/images/my-image.jpg" />';
</script>

If you want to pass some data from PHP to JS use echo:

<script type="text/javascript">
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="<?php echo $image ?>" />';
</script>

where $image-php variable. In general you may generate any JS code using PHP as well as html.

To pass data from JS to PHP (from client to server) use AJAX

I hope this will help.



回答2:

Your question is very ambigious, its not clear what you are asking. Please edit and refine your question as soon as you learn something from a comment or an answer.

First of all, as poined out by webdeskil in comments, you can indeed call PHP code from client side and in fact that is done very often. What you can not do is executing PHP code "ON" the client side. Any request for executing server side code, in this case PHP has to go to the server where it can, and it makes sense for it, to be executed.

From your tags it looks like you are writing some code for wordpress. IMHO a good way of learning programming skills is to look at existing code. Since wordpress is opensource, you have the luxury of being able to open any plugin or theme and take a look inside. However, the number one resource for your wordpress needs is the codex of course. Read the codex document carefully, in this case codex document for using javascript is relevant to your question.

Some tips that maybe helpful:

  • You should avoid writing javascript file where php can do the same thing
  • If you use JQuery, you should know that wordpress already loads an instance of JQuery for you and you should avoid loading another instance if you can

Anyway, to give you any more help you need to edit and refine your question further, otherwise its all guesswork for us trying to help.