我需要将一些 JS 变量传递给 PHP,但遇到了一些麻烦。
我尝试了以下方法:
$product_id = "<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id')</script>";
echo $product_id;
但这只是将它打印为一个字符串:
`<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id');</script>`
我将如何存储该 JS 变量,然后使用 PHP echo
它?我是 PHP 的新手,所以任何帮助将不胜感激!
最佳答案
按照您的方式进行,这是不可能的。 PHP 无法在同一页面中直接“读取”javascript 或“与之交互”。
你要明白PHP是一个预处理器,它在服务器端生成HTML,然后生成的页面发送给客户端。在此页面中,PHP 代码已完全消失。您只能看到它生成的内容(即 HTML 或 JS)。然后,javascript 代码运行,它不知道它是使用 PHP 生成的,也不知道 PHP 的存在。
为了将变量传递给 PHP 脚本,您必须使用 GET 或 POST 方法调用文件:
(JS)
$.get( 'myScript.php', { // This is calling the PHP file, passing variables (use get or post)
variable1 : "Hello",
variable2 : "world!"
}, function(data){ // PHP will then send back the response as "data"
alert(data); // will alert "Hello world!"
});
(myScript.php)
$variable1 = $_GET['variable1']; // or POST if you're using post
$variable2 = $_GET['variable2'];
echo $variable1 . " " . $variable2; // Concatenates as "Hello world!" and prints it out.
//The result of the PHP file is sent back to Javascript when it's done.
当然,这是一个非常基本的例子。永远不要直接阅读和使用发送到 PHP 的内容(就像我刚才所做的那样),因为任何人都可以注入(inject)他们想要的任何东西。 Add securities .
关于javascript - 如何用 PHP 打印 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28826910/