获取一个javascript变量到php

时间:2014-04-05 11:24:57

标签: javascript php

我有这段代码:

<script type="text/javascript" charset="utf-8" src="http://web.itoday.gr/load.js"</script>
<p><script type="text/javascript"> datesmart(0); namesprefix(0); names(0); </script></p>
<p><script type="text/javascript"> datesmart(1); namesprefix(1); names(1); </script></p>

我想将变量名(1)变为php变量。我怎么能这样做? 非常感谢!

2 个答案:

答案 0 :(得分:1)

您无法直接访问PHP中的JS变量。你有两个选择

1)将names(1)的值设置为html元素并访问该html元素的值(如隐藏字段,跨度等)

2)使用AJAX

举个例子:

如果您使用表单将值提交到其他页面,请添加隐藏字段。

<input type="hidden" id="nameval">

使用hiddenspan等元素代替div字段,在html页面中显示names(1)的值,例如

<span id="nameval"></span>

使用jquery设置此隐藏输入字段的值(以及span / div的html)。根据需要适当调用此功能。首先,您需要包含jquery库,如下所示。

<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>    
<script type="text/javascript">
$(document).ready(function()     // when the document is ready
{
    $("#nameval").val(names(1));    // set the value of element with id nameval if you are using hidden field

    $("#nameval").html(names(1));   // use this in the case of span/div
});
</script>

答案 1 :(得分:0)

PHP在浏览器中运行服务器和javascript。您需要发送ajax请求以从javascript访问值。

在脚本加载时,将带有数据的ajax请求发送到要访问此变量的php脚本。