如何使用PHP打印JavaScript


How to print JavaScript with PHP

我需要将一些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的内容(就像我刚刚做的那样),因为任何人都可以注入他们想要的任何内容。添加证券。

JavaScript在客户端运行,而PHP在服务器上运行。它们在页面生命周期中的执行时间完全不同,因此无法以您使用的方式进行通信。

相反,您可以使用AJAX将JS中的值发送到PHP页面。

感谢您的帮助,非常感谢!我已经按照建议使用ajax完成了这项工作:

<script type="text/javascript">
jQuery("document").ready(function(){
    var $ = jQuery
    $("form").submit(function(){
        var data = "";
        data = $(this).serialize() + "&" + $.param(data);
        var prod_id_one =   $('#prod1').val();
        var prod_id_two =   $('#prod2').val();
        var prod_id_three = $('#prod3').val();
        var prod_id_four =  $('#prod4').val();
        $.ajax({
            type: "GET",
            url: "my_ajax_url_here", 
            data: data,
            success: function(data){ 
                window.location = "price-calculator?width="+ $('#wpti-product-x').val() + "&height=" +  $('#wpti-product-y').val() + "&id1=" + prod_id_one + "&id2=" + prod_id_two + "&id3=" + prod_id_three + "&id4=" + prod_id_four;
            }
        });
        return false;
    });
});
</script> 

它现在正在使用上面的代码。再次感谢!