我需要将一些 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 变量然后echo
它使用 PHP 吗?我对 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 的内容(就像我刚才所做的那样),因为任何人都可以注入他们想要的任何内容。添加证券 http://www.dreamhost.com/dreamscape/2013/05/22/php-security-user-validation-and-sanitization-for-the-beginner/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)