2016-07-30 96 views
-1

我使用JavaScript來觸發我的餅乾,我已經被告知,使用PHP the most reliable method to set cookies is to create them on the server side ...如何設置一個PHP cookie被創建onclick事件

我已經測試此代碼,但它創造了

<a href="<?php 
if (!isset($_COOKIE['my_test_cookie'])) { 
ob_start(); 
setcookie("my_test_cookie", "1", time()+ (86400 * 90), "/"); 
ob_end_flush(); 
}?>" onClick="javascript:HideContent('div3');">Create Cookie</a> 

是否有可能建立在PHP中的cookie,只創造了他的onclick事件:在頁面加載,我需要它的cookie只有當用戶點擊一個鏈接來設置?

如:< href="#" onclick="call_the_php_function_where_we_setup_the_cookie_variables();">click here to create the cookie</a>

回答

0

PHP是之前的頁面曾經被客戶端瀏覽器看到的服務器上運行。在頁面發送到客戶端後,沒有任何方法讓PHP代碼運行。

唯一的解決辦法是在後臺點擊按鈕來加載一個php頁面,在你想要的背景中使用AJAX。

例如,你可以設置你的網頁運行這樣的按鈕被按下時:

var req = new XMLHttpRequest(); 
req.addEventListener("load", function() { 
    console.log(this.responseText); 
}); 
req.open("GET", "http://yoursite.com/path_to_cookie_setter_page"); 
req.send();