Run PHP code inside JavaScript? Would this be ok to use?

前端 未结 4 1716
孤街浪徒
孤街浪徒 2021-01-21 03:43

I am not sure if a line of PHP could be run inside of a JavaScript function. For example:



        
4条回答
  •  猫巷女王i
    2021-01-21 04:26

    Let's talk about fundamentals :)

    PHP is a language that, in this case, runs on your web server. It produces the web page that people see, and all of that PHP code is already completely done by the time the page makes it to the user. It runs on the server, and the server only: not the web browser.

    Javascript is a language that, in this case, runs on a user's web browser. It provides basic interactivity with what data it is given by the time the page is created, and cannot interact with your database directly. Javascript runs on the web browser, and the web browser only: not the server.

    Since the database is on the server, and Javascript cannot access things on the server, Javascript must send an HTTP request in order to communicate with the server in order to access the database. In this case, that means an AJAX request. Since PHP is your server-side language, that will mean creating a PHP script to fetch what you need from the database, and putting it in a form for the Javascript to read, likely using PHP's json_encode to produce the format and something like jQuery's $.getJSON to fetch and decode that data.

    All of the different languages we have to use on the web can make things a bit tricky. It might be worth trying to get a better understanding of how the web works before embarking on big projects… but I wish you the best of luck!

提交回复
热议问题