简体   繁体   English

将变量从 javascript 传递到 php

[英]passing variables from javascript to php

i am passing variable from javascript php with the following code by using cookie.我正在通过使用 cookie 使用以下代码从 javascript php 传递变量。

<script type="text/javascript">
function gTest() {
               var country = 'hello testing';
    document.cookie = 'name=document.write(country);' ; 
         document.write(country);
}
gTest();
</script>


<?php  
echo "<br>";
     var_dump($_COOKIE['name']);  
?> 

it works fine if we change to如果我们改为

    document.cookie = 'name=hello' ; 

i want to pass variable value to php in same page...i don't want to send to another page.我想在同一页面中将变量值传递给 php...我不想发送到另一个页面。

thanks谢谢

$_COOKIE is populated with the data sent from the browser to the server. $_COOKIE填充了从浏览器发送到服务器的数据。

The JS to change the cookie won't run until the response is sent back and the JavaScript is executed.在响应被发回并执行 JavaScript 之前,更改 cookie 的 JS 不会运行。

The values in $_COOKIE won't update until you make a new HTTP request.在您发出新的 HTTP 请求之前, $_COOKIE _ $_COOKIE的值不会更新。

You can use XHR.您可以使用 XHR。

JavaScript (using jQuery): JavaScript(使用 jQuery):

$.ajax('script.php', { 
    data: { 'name': 'hello' }
});

PHP: PHP:

 var_dump($_GET['name']);

You cant.你不能。

Ok, I think I got to explain.好吧,我想我得解释一下。 On your page, there is the Javascript first, then the PHP code, but it doesnt execute in that order.在您的页面上,首先是 Javascript,然后是 PHP 代码,但它不会按该顺序执行。 First the server execute the PHP code, send the page as HTML and the javascript is executed on the client side.首先服务器执行 PHP 代码,将页面作为 HTML 发送,然后在客户端执行 javascript。

If you really dont want to reload the whole page, the only way to do it is to use an ajax request to a page where your PHP code is.如果您真的不想重新加载整个页面,那么唯一的方法是对您的 PHP 代码所在的页面使用 ajax 请求。 Simply use JQuery and replace your PHP code with this :只需使用 JQuery 并将您的 PHP 代码替换为:

$('#result').load('showCookie.php');

Content of showCookie.php will be your var_dump and the page will do exactly what you want, except that you have called an additional page with JQuery. showCookie.php 的内容将是您的 var_dump 并且该页面将完全按照您的要求执行,除了您使用 JQuery 调用了一个附加页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM