setcookie("MyCookie",$value); // Sets the cookie to the value,remember,do not Set it with HTTP only to true.
[/list]然后,你可以用它JavaScript阅读使用document.cookie:
这是一个简短的手动分析器,但我对上面链接的答案有更好的测试:
[list=1]var cookies = document.cookie.split(";"). map(function(el){ return el.split("="); }). reduce(function(prev,cur){ prev[cur[0]] = cur[1]; return prev ,{};alert(cookies["MyCookie"]); // Value set with PHP.
我在这里的回答解释了如何在 JavaScript 中使用 AJAX 加载数据:[code]function callback(data){ // What do I do with the response?}var httpRequest = new XMLHttpRequest;httpRequest.onreadystatechange = function(){ if (httpRequest.readyState === 4) { / Request is done if (httpRequest.status === 200successfully callback(httpRequest.responseText); // We're calling our method }httpRequest.open('GET',"/echo/json");httpRequest.send();: o Y H. e. \) _' _
或者使用 jQuery:2 q! q9 J1 H: Q& [- N- ]( M. R
$.get("/your/url").done(function(data){ / What do I do with the data?}); 7 |* g0 _ w: H; K+ v
现在服务器只需要包含一个/your/url路在您的情况下,由/文件包含获取数据并处理数据的代码:% m. i- K+ v" f1 t9 i
getValue(); // Makes an API and database callheader("Content-Type: application/json"); // Advise client of response typeecho json_encode($val); // Write it to the output g9 h& Z+ t+ k( E