加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax初级 json_encode

发布时间:2020-12-16 02:03:40 所属栏目:百科 来源:网络整理
导读:Ajax:Asynchronous JavaScript and XML Ajax用来异步通信,用户不需要长长的等待。 实现也很简单,主要用到XMLHttpRequest对象 HTML代码: body form pCity: input type="text" name="city" id="city" size="25" onChange="callServer();" //p pState: inpu

Ajax:Asynchronous JavaScript and XML

Ajax用来异步通信,用户不需要长长的等待。

实现也很简单,主要用到XMLHttpRequest对象

HTML代码:

<body>

<form>
<p>City: <input type="text" name="city" id="city" size="25"
onChange="callServer();" /></p>
<p>State: <input type="text" name="state" id="state" size="25"
onChange="callServer();" /></p>
<p>Zip Code: <input type="text" name="zipCode" id="zipCode" size="5" /></p>
</form>

</body>

<script>

var XMLHttp= null ;//兼容多种浏览器
try {
new ActiveXObject( "Msxml2.XMLHTTP" );
} catch (e){
{
"Microsoft.XMLHTTP" );
}
}
if (XMLHttp== ){
XMLHttpRequest();
}

function callServer(){
var city=document.getElementById("city").value;
var state=document.getElementById("state").value;
if((city==null)||(city=="")) return;
if((state==null)||(state=="")) return;
var url="__APP__/Index/test2?city="+escape(city)+"&state="+escape(state);//这里用的thinkphp框架,一般是xx/yy/z.php
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=updatePage;
xmlHttp.send(null);
}
function updatePage(){
if (xmlHttp.readyState==4) {
if (xmlHttp.status==200){
var response=xmlHttp.responseText;
document.getElementById("zipCode").value=response
;

}
}

</script>


后台PHP:

public function test2(){

//获得来自 URL 的参数

$c=$_GET["city"];
$s=$_GET["state"];


//查找数组中的所有提示
if ((strlen($c) > 0)&&(strlen($s) > 0)){
$response = 112;
echo $response;
}

}

后台处理后的数据放到$response(这只是随便取的变量名,可以改的)里

然后前台的updatePage函数通过xmlHttp.responseText获取,就行啦~

如果要传数组,就要用json格式,比如:

$response=("1","2","3");

echo json_encode($response);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读