欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP 與 js的通信(via ajax,json)

 更新時(shí)間:2010年11月16日 23:03:44   作者:  
一定要設(shè)置xmlHttp.setRequestHeader,否則傳往PHP的參數(shù)會(huì)變成null(line 38)
JavaScript端:
注意:一定要設(shè)置xmlHttp.setRequestHeader,否則傳往PHP的參數(shù)會(huì)變成null(line 38)
亮點(diǎn)在line 31!
復(fù)制代碼 代碼如下:

<script type="text/javascript">
function GetJson() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {

try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("您的瀏覽器不支持AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
//alert(xmlHttp.responseText);
var str = xmlHttp.responseText;
document.getElementById('show').innerHTML +=str;
//alert(str);
var obj = eval('('+ xmlHttp.responseText +')');
//var obj = eval(({"id":"123","name":"elar","age":"21"}));
alert(obj.name);
}
}
var data = "id=123";
xmlHttp.open("POST", "testJson.php", true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("id=123");
}
</script>
<input type="button" onclick="GetJson()" value="按我!"/>
<hr />
<div id="show"></div>

PHP端【testJson.php】:
(注意,php文件要干凈,<?php ?>標(biāo)簽的外部不能有其他標(biāo)簽,否則eval函數(shù)無(wú)法解析)
亮點(diǎn)在line 6
復(fù)制代碼 代碼如下:

<?php
$res['id'] = $_POST['id'];
$res['name'] = "elar";
$res['age'] = "21";
$response = "hello this is response".$_POST['id'];
echo json_encode($res);
?>

總結(jié):
js要往PHP端送數(shù)據(jù),用的是xmlHttp.send("id=123");
PHP給js送數(shù)據(jù),用的是echo json_encode($res);(要注意變量$res的構(gòu)造應(yīng)符合JSON的規(guī)范)
js要解析PHP送來(lái)的JSON格式的數(shù)據(jù),用var obj = eval('('+ xmlHttp.responseText +')');

相關(guān)文章

  • JavaScript 滾輪事件使用說(shuō)明

    JavaScript 滾輪事件使用說(shuō)明

    用過(guò) Google 地圖的人可能都很熟悉,通過(guò)滾動(dòng)滾輪可以對(duì)地圖進(jìn)行縮放,非常地方便。適當(dāng)?shù)厥褂脻L輪事件可以帶來(lái)不錯(cuò)的用戶體驗(yàn)。
    2010-03-03
  • 最新評(píng)論