通過這樣做,這是不可能的。 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。
PHP是服務器端,JavaScript是客戶端。 PHP所做的工作是在Javascript之前進行的。如果你想傳遞一些信息,如你所說的「從Javascript到PHP」,你必須向服務器發出請求(例如通過鏈接,表單或Ajax調用)。 – Danilo 2015-03-03 08:15:09
我認爲它應該像你這樣做。你是否在使用框架,並且可以確保你的代碼中沒有像'htmlspecialchars'這樣的東西? – 2015-03-03 08:18:32
謝謝。 @ Pierre-Jean沒有特殊的框架,也沒有'htmlspecialchars'。我將不得不重新考慮上一步並重新做一點。 – wper 2015-03-03 08:21:33