把php数据或值传递给js
很简单,直接在js中使用php代码,混编即可。
var x = <?php echo 'xx';?>
把js数据传递给php
可以使用打开新窗口或重新定位的方式,通过url地址把数据传递过去。php通过$_GET获得
window.open('location.href=xx.php?id='+x);
location.href=xx.php?id=x;
可以使用form表单提交。php通过$_GET获得
document.form.submit();
可以使用ajax,通过get或post传递给php
最后也可以保存cookie让php来读(这个一般没用)。
在传递数据过程中可能遇到中文编码 问题,可以统一编码方式为js的escape,unescape,也可以统一编码方式为urlencode,urldecode
由于php有函数urlencode,urldecode,这个时候需要js来实现该编码,下面是js的编码
function UrlEncode(str)
{
var ret="";
var strSpecial="!/"#$%&()*+,/:;<=>?[]^`{|}~%"; var tt="";
for(var i=0;i
{
var chr = str.charAt(i);
var c=str2asc(chr);
tt += chr+":"+c+"n";
if(parseInt("0x"+c) > 0x7f)
{
ret+="%"+c.slice(0,2)+"%"+c.slice(-2);
}
else
{
if(chr==" ")
ret+="+";
else if(strSpecial.indexOf(chr)!=-1)
ret+="%"+c.toString(16);
else
ret+=chr;
}
}
return ret;
}
UrlDecode
function UrlDecode(str){
var ret="";
for(var i=0;i
{
var chr = str.charAt(i);
if(chr == "+")
{
ret+=" ";
}
else if(chr=="%")
{
var asc = str.substring(i+1,i+3);
if(parseInt("0x"+asc)>0x7f)
{
ret+=asc2str(parseInt("0x"+asc+str.substring(i+4,i+6)));
i+=5;
}
else
{
ret+=asc2str(parseInt("0x"+asc));
i+=2;
}
}
else
{
ret+= chr;
}
}
return ret;
}
由于js有函数escape和unecapse,需要php来实现该编码,下面是php的编码
function unescape ($source) {
$decodedStr = "";
$pos = 0;
$len = strlen ($source);
while ($pos < $len) {
$charAt = substr ($source, $pos, 1);
if ($charAt == '%') {
$pos++;
$charAt = substr ($source, $pos, 1);
if ($charAt == 'u') {
// we got a unicode character
$pos++;
$unicodeHexVal = substr ($source, $pos, 4);
$unicode = hexdec ($unicodeHexVal);
$entity = "". $unicode . ';';
$decodedStr .= utf8_encode ($entity);
$pos += 4;
}
else {
// we have an escaped ascii character
$hexVal = substr ($source, $pos, 2);
$decodedStr .= chr (hexdec ($hexVal));
$pos += 2;
}
} else {
$decodedStr .= $charAt;
$pos++;
}
}
return $decodedStr;
}
jsp和js通讯和上面过程类似
直接混编
jsp通过request.getParameter()获取get或post传递的参数