php如何传值给js

JavaScript012

php如何传值给js,第1张

很简单。。。举例

$message = "这是一个来自 php 的值。"

echo "<script language=\"JavaScript\" type=\"text/JavaScript\">\r\n<!--\r\n alert('".$message."')\r\n-->\r\n</script>"你得把所有的JS代码转成PHP格式就可以了。

JS向PHP传递数值只有两种方法:GET和POST,GET把参数写在URL上,例如abc.php?param=123,POST的参数在数据里面。

JS调用PHP(无论GET或者POST)一般有两种方式,一是是用HTML窗口,使用GET的例子:

<iframe src=abc.php?param=123></iframe>

使用POST的例子:

<form action=abc.php method=post name=form1>

<input type=hidden name=param value=123>

</form>

<script language=javascript>

form1.param.value=123

form1.submit()

</script>

JS调用PHP(无论GET或者POST)的另外一种方式是是用AJAX,例子代码网上很多,我写一个最简单的:

<script language=javascript>

  var xmlHttp=null

  if (window.ActiveXObject) xmlHttp=new ActiveXObject('Microsoft.XMLHTTP')

  else if (window.XMLHttpRequest) xmlHttp=new XMLHttpRequest()

  xmlHttp.onreadystatechange=handleStateChange

  xmlHttp.open('POST','abc.php')

  xmlHttp.send('param=123')

function handleStateChange(){

  if (xmlHttp.readyState==4){

    if (xmlHttp.status==200){

      alert(xmlHttp.responseText)

    }

  }

}

</script>