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

前端 未结 4 1711
孤街浪徒
孤街浪徒 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条回答
  • 2021-01-21 04:14

    You need to print something with php. I don't understand what you are trying to do. You can use php inside javascript for templating but I suggest you use ajax.

    I would use jQuerys .ajax() function on the javascript side and echo json_encode($result_array) on the php side.

    0 讨论(0)
  • 2021-01-21 04:16

    No - the query will be ran once on the server, and the JavaScript will call an empty function.

    Note, you should be using just message there, otherwise JavaScript's eval() is being called internally.

    0 讨论(0)
  • 2021-01-21 04:23

    You're getting it the other way around. Your main file is PHP, and the PHP parser will interpret that and create a HTML page out of it, which may or may not contain JavaScript. This file will be sent to the client, and the client will then interpret any JavaScript.

    JavaScript = client side.

    PHP = server side.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题