当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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

<script language=javascript>

var int=self.setInterval("message()",1000);

function message()

{

<?PHP mysql_query("SELECT * FROM example"); ?>

}

</script>

I haven't tried to run this, but I don't think you can run PHP like this. Could anyone help. Could i run a PHP script inside a javascript function somehow without using a call to an outside PHP file through Ajax?

网友答案:

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!

网友答案:

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.

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: