2015-03-03 88 views
1

我需要將一些JS變量傳遞給PHP,並遇到一些麻煩。如何使用PHP打印JavaScript

我曾嘗試以下:

$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很新,所以任何幫助將不勝感激!

+1

PHP是服務器端,JavaScript是客戶端。 PHP所做的工作是在Javascript之前進行的。如果你想傳遞一些信息,如你所說的「從Javascript到PHP」,你必須向服務器發出請求(例如通過鏈接,表單或Ajax調用)。 – Danilo 2015-03-03 08:15:09

+0

我認爲它應該像你這樣做。你是否在使用框架,並且可以確保你的代碼中沒有像'htmlspecialchars'這樣的東西? – 2015-03-03 08:18:32

+0

謝謝。 @ Pierre-Jean沒有特殊的框架,也沒有'htmlspecialchars'。我將不得不重新考慮上一步並重新做一點。 – wper 2015-03-03 08:21:33

回答

2

通過這樣做,這是不可能的。 PHP不能在同一頁面直接「閱讀」或「與」javascript「交互」。

你必須明白,PHP是一個預處理器,它在服務器上生成HTML,然後生成的頁面被髮送到客戶端。在這個頁面中,PHP代碼完全消失了。您只能看到它生成的內容(即HTML或JS)。然後,JavaScript代碼運行,並且它不知道它是使用PHP生成的,也不知道PHP的存在。

爲了變量傳遞給PHP腳本,你必須調用與GET或POST方法文件:

$.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)

(JS)

$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的內容(就像我剛剛那樣),因爲任何人都可以注入任何他們想要的東西。 Add securities

+0

感謝您的全面回答。 – wper 2015-03-03 09:22:04

+0

不用擔心。如果你覺得它很有價值,如果你驗證了它,我將不勝感激:) – 2015-03-03 09:26:26

0

當PHP運行在服務器上時,JavaScript運行在客戶端。它們在頁面生命週期中完全不同的時間執行,因此它們無法以您使用的方式進行通信。

相反,您可以使用AJAX將JS中的值發送到PHP頁面。

+0

謝謝。我會嘗試一些想法。 – wper 2015-03-03 08:22:26

0

感謝您的協助,非常感謝!我已經設法按照建議使用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> 

它現在正在使用上面的代碼。再次感謝!