links for 2008-07-20

美味书签No Comments »

Related posts

links for 2008-07-19

美味书签No Comments »

Related posts

PHP与Javascript间的参数传递

编程相关No Comments »

通常情况下,Javascript是客户端技术,而PHP 是服务器端技术,而且HTTP 是一种“无状态”协议,因此两种语言之间不能直接共享变量。

但往往有时候需要在两者之间进行参数传递,可以通过以下变通的方法实现。

一、从PHP传变量到Javascript

1
2
3
4
< ?php
    //在PHP中定义变量并赋值
    $MyPHPVar = "PHPVar";
?>

直接使用PHP的变量,只需将PHP变量输出为字符串就可以赋值给Javascript的变量即可

1
2
3
4
5
<script type="text/javascript">
    //要注意的是,Javascript的位置要在PHP变量定义之后,才能调用该变量 
     var MyVar = < ?php echo $MyPHPVar; ?>;
     alert (MyVar);
</script>

另一个较复杂的例子

1
2
3
4
function addname(){
location.href = "< ?php print($_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'].'&username=');?>"
+document.form1.username.value;
	}

二、从Javascript传参数到PHP
需要用 PHP 生成 Javascript 代码,并让浏览器自动刷新,将特定的变量传递回 PHP 脚本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< ?php
  //页面刷新后获得从URL传递过来的变量
if (isset($_GET['width']) AND isset($_GET['height'])) {
  //输出变量
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  echo "<script language='javascript'>\n";
  //在PHP中生成Javascript, 用刷新页面的方式将变量通过URL传递给PHP
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>

Related posts

links for 2008-07-10

美味书签No Comments »

Related posts

links for 2008-07-09

美味书签No Comments »

Related posts

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in