Как выполнить PHP-код в JavaScript
Вы можете использовать http://phpjs.org/ http://locutus.io/php/ он передает кучу функциональности PHP в javascript, но если это просто эхо, а script находится в php файле, вы можете сделать что-то вроде этого:
не волнуйтесь о сменном использовании двойных кавычек, PHP сделает это до того, как браузер увидит его.
как для использования ajax, самый простой способ — использовать библиотеку, например jQuery. С этим вы можете сделать:
он будет писать содержимое test.php любому элементу класса result .
Взаимодействие Javascript и PHP
Мы все выросли, зная, что Javascript работает на стороне клиента (то есть в браузере) и PHP — это серверный инструмент (то есть сервер). ОЧИСТНО, что оба просто не могут взаимодействовать.
Но — хорошие новости; его можно заставить работать и вот как.
Цель состоит в том, чтобы получить некоторую динамическую информацию (например, элементы конфигурации сервера) с сервера в среду Javascript, чтобы ее можно было использовать при необходимости — обычно это подразумевает изменение DHTML в презентации.
Во-первых, чтобы прояснить использование DHTML, я приведу этот пример DHTML:
Предположим, что у нас есть html файл с где-то, то мы можем изменить дисплей с помощью простого < body onload = «updateContent()» >
Golly gee; нам не нужен PHP, чтобы делать это сейчас! Но это создает структуру для используя PHP предоставленный контент.
Мы меняем рассматриваемую веб-страницу на тип PHTML, чтобы разрешить доступ к PHP на стороне сервера к контенту:
и мы добавим в начало этой страницы. Мы также вызываем загрузку данных php в глобальные списки для последующего доступа — — вот так:
Теперь наши javascripts могут перейти к глобальным глобалиям PHP следующим образом:
//путем доступа к глобальным переменным var textMsg = ‘<? php global $textMsgPHP; echo «$ textMsgPHP»;? > ‘;
В javascript замените
var textMsg = ‘Сказать доброе ночное убийство’;
с: // используя php returnContent()
var textMsg = ‘<? php $msgX = returnContent (‘dummy_div_data_3.txt’); echo «$ msgX»? > ‘;
- веб-страница, подлежащая изменению, ДОЛЖНА быть файлом phtml или некоторым php файлом.
- первое, что в этом файле ДОЛЖНО быть <? php для получения динамических данных? >
- данные php ДОЛЖНЫ содержать собственный CSS-стиль (если контент находится в кадре)
- javascript для использования динамических данных должен находиться в этом же файле
- и мы заходим в/из PHP по мере необходимости для доступа к динамическим данным
- Обратите внимание: — используйте одиночные кавычки во внешних javascript и двойные кавычки ONLY в динамических php-данных.
Будет разрешено: вызывать updateContent() с именем файла и используя его через onClick() вместо onLoad()
Выполнение PHP-кода в файлах JavaScript
В большинстве веб-приложений статические JavaScript-файлы устраивают разработчика на 100%. Однако же иногда бывает лучшим решением подключить PHP и сгенерировать содержимое JS-файла «на лету» (например, получить актуальные цены на продукты из БД и передать их JavaScript-программе для валидации формы заказа). Как же это сделать?
Способ первый: простой
Конечно же, самое простое решение состоит в том, чтобы включить код PHP внутрь секции вашего HTML-шаблона, поскольку есть шансы, что у него будет расширение .php.
Даже если расширение шаблона .htm или .html, то в большинстве случаев веб-сервер настроен так, чтобы понимать включения PHP-кода (если же нет, то в конце заметки есть простой пример как решить и эту проблему). Но что касается красоты, то этот вариант не самый изящный. Хорошо бы держать мух и котлеты раздельно.
Способ второй: красивый
Второй вариант решения — настроить веб-сервер так, чтобы он парсил JavaScript-файлы на предмет выполнения PHP-кода. Достаточно создать в нужной папке файл .htaccess или открыть уже существующий и добавить в него следующие строки:
Pro et Contra: что нам это дает?
- Вы можете включать PHP-код в файлы с расширением .js и он автоматически выполнится при клиентском обращении к JavaScript-файлу.
- Вы можете держать такие «гибридные» скрипты в отдельной папке — достаточно в эту папку поместить описанный выше файл .htaccess.
- Если вы хотите держать все JavaScript-файлы в одном месте (статические и гибридные), то можете зарегистрировать обработчик файлов с произвольным расширением, например, .js2 — достаточно немного модифицировать текст .htaccess.
- Вы можете разделить статические HTML-страницы, шаблоны и JavaScript-файлы.
- Теоретически это вызовет минимальную дополнительную нагрузку на работу сервера, но, учитывая вариации с отдельными папками или расширениями файлов, польза кажется превосходящей.
Дополнение
Для того, чтобы веб-сервер парсил файлы .htm и .html и выполнял включенный в них PHP-код, нужно добавить в .htaccess следующие строки:
How do I embed PHP code in JavaScript?
![]()
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don’t want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you’d do something like this:
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
Running PHP in Javascript
But why? you are wondering. You must be given some context: this is an experiment inside another experiment I'm doing to learn about Static Site Generators. PHP is the first language I knew well and I wanted to test whether it's a horrible or just a bad idea to use it for templates.
If you come from Google trying to find how to run PHP inside Javascript, you are very likely lost. Beware, this article is only for experts! /s
Since a large motivator for my site generator is to rely purely on Node.js and not to have to install Ruby, I also don't want to install PHP! But can you run PHP inside Javascript? I only need the most basic PHP features: variables, echo, loops.
The sarcastic language of this article might be deceiving, but there is a working demo below.
Initial objective
The idea came when I was making FrontMatter work properly for the current file. It is also related to my general dissatisfaction with the Node.js template engines, but that a topic for another day:
It reminded me quite a bit to what can be achieved with raw PHP:
Googling around
Google just led me to 780 StackOverflow questions with -1 average score. After reading some, I believe the average score should be more like -5 . I also learned that devs are trying to do:
As an astute reader might notice, that is supposed to run first through the PHP server, then sent to the browser and finally run the resulting alert("Hello world") on the client. But this level of sophistication is too high, I just want to run raw PHP on the browser! I want something like this:
Promising finds
After getting lucky with a "PHP parser Javascript" search, I end up finding the package php-parser in Github/npm. The problem is that the output is an Abstract Syntax Tree. I just wanted to run the code, not whatever an abstract tree seems to be:

Since you are reading this it means that in the Related Projects category I found my next clue. I head to the website with the funny looking cat : babel-preset-php . It transpiles PHP into Javascript
Since babel is in total chaos with the whole babel-loader vs @babel/loader and no one knows which one is which (ironic, innit?), I give up and take a break. I do practice my Kanjis, speak with my family in Spanish and think about the English title for this article.
Building up the library
Fresh again, I scavenge the library babel-preset-php for my project. I am now using:
- php-parser to transform the PHP into the Abstract Tree thing.
- babel-preset-php ravaged files to do something that I have no idea what it is but it's the only way to keep it working.
- @babel/generator to finally generate the Javascript from the previous step.
- A bit of Javascript. I use the fancier new Function() to pretend it's better than eval() .
I wasn't going to show you, but since my code is so tiny thanks to those great libraries I can just paste it here for your satisfaction:
Later on I will export some individual parts for better testing, but that is really all there is to it.
The long-awaited demo! Turn your internet off, hide your kids and say your prayers. I already loaded the php() function for you, but are you ready to run it?
Tips to make the demo better for lack of documentation:
- Use backticks as the first argument of php() to allow for any quote type and multi line.
- Provide a second argument as a plain object like < hello: 'world' >to define the variable $hello with the value "world" inside the PHP code.
- If you want to run it with express use < _GET: req.query, _POST: req.body >as the second argument (do not do it, specially on a live server).
- You could pass window as the second argument as well if you prefer PHP instead of Javascript. Heck, you could make a tool that finds and runs all <script src="ohmy.php" type="application/php"></script> .
- I am running eval() against your code. The php() function is basically running eval() internally. Do I get a "Go to Jail card" for basically doing eval(eval(. )) ?
Closures
Yup, this sucks. Use it just as an example of things that should never happen. If you really, really need to use this, and want more features, feel free to throw me loads of money and I might consider talking you out of it or contacting the relevant health authorities.
Now that we have reached this point and seeing how many languages have AST generators, I ponder: can any language be transpiled to Javascript? Should we do it? Webassembly is going to eat JS so we might just give it a try!
If you hate PHP, or Javascript, and you really want to let me and others know* feel free to comment on Hacker News: