简体   繁体   English

我可以在javascript中使用php吗?

[英]Can I use php in javascript?

Begginer's question. 贝金纳的问题。

Can I use PHP in javascript? 我可以在JavaScript中使用PHP吗?

For example in jquery, 例如在jquery中,

...
...
triggers.eq(1).post('<?php admin/categories/delete/'. $list['id']; ?>);

PHP is executed on the server side and JavaScript on the client side. PHP在服务器端执行,JavaScript在客户端执行。 But you can print the PHP variable like this: 但是您可以这样打印PHP变量:

triggers.eq(1).post(<?php echo json_encode('admin/categories/delete/'. $list['id']); ?>);

And then the output is like: 然后输出就像:

triggers.eq(1).post('admin/categories/delete/12345');

What you want to do is possible, if the javascript is in an PHP file, 如果javascript在PHP文件中,那么您想做的事就可以了,

triggers.eq(1).post('admin/categories/delete/<?= $list['id'] ?>');

The PHP doenst run in the javascript, but the variable is replaced when the page is sent to the client. PHP doenst在javascript中运行,但是在将页面发送到客户端时替换了该变量。

php runs on the server. php在服务器上运行。

typically, javascript runs in a browser. 通常,javascript在浏览器中运行。

You can use jQuery to make a request for an url which is handled by php, and thus have jQuery delete! 您可以使用jQuery来请求由php处理的网址,从而删除jQuery!

No, You cannot send query that way. 不,您不能以这种方式发送查询。 Even you can send php codes to server, and exec it, its not secure way. 即使您可以将php代码发送到服务器并执行它,这也不安全。

No, you cannot use PHP within JavaScript. 不,您不能在JavaScript中使用PHP。 Think about it this way: you need a PHP interpreter/runtime to execute the PHP, and browsers do not contain this. 这样考虑:您需要一个PHP解释器/运行时来执行PHP,而浏览器不包含此内容。 Based on your code snippet above, you could instead send an ajax call to a PHP script on the server. 根据上面的代码片段,您可以改为将ajax调用发送到服务器上的PHP脚本。

I suppose you could pass PHP code to a server-side script and interpret/execute it, but you'd still need ajax or a full GET/POST request, and it would never be a good thing to do because of how easy it would be for malicious code injection. 我想您可以将PHP代码传递到服务器端脚本并解释/执行它,但是您仍然需要ajax或完整的GET / POST请求,由于这样做很容易,所以这绝不是一件好事用于恶意代码注入。

You can use PHP to write your javascript. 您可以使用PHP编写JavaScript。
You can't execute PHP client-side - so no, you can't use php in your javascript code. 您无法执行PHP客户端-因此,您不能在JavaScript代码中使用php。

Rename your files with the extension of PHP and then you can use PHP code inside of your file. 使用PHP扩展名重命名文件,然后可以在文件内部使用PHP代码。

Another solution to tell your server to render your JS files as PHP script. 告诉服务器将JS文件呈现为PHP脚本的另一种解决方案。 For some performance and security reasons it's not recommended. 由于某些性能和安全原因,不建议使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM