当前位置: 移动技术网 > IT编程>开发语言>Java > AJAX 自学练习 请求与显示

AJAX 自学练习 请求与显示

2017年12月12日  | 移动技术网IT编程  | 我要评论
如下:
request.jsp
复制代码 代码如下:

<%@ page language="java" contenttype="text/html; charset=iso-8859-1"
pageencoding="iso-8859-1"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
<script language="javascript"><!--
function getxmlhttpobject(){
    var xmlhttp = null;
    try{
        xmlhttp = new xmlhttprequest();
    }catch(e){
        try{
            xmlhttp = new activexobject("msxml2.xmlhttp");
        }catch(e){
            xmlhttp = new activexobject("microsoft.xmlhttp");
        }
    }
    return xmlhttp;

}
function showmsg(str){
    xmlhttp = getxmlhttpobject();
    if(xmlhttp == null){
        alert ("you browser don't support the ajax");
         return;

    }
    var url = "response.jsp";
    url = url + "?q="+ str;
    url = url + "&sid ="+ math.random();
    xmlhttp.onreadystatechange = statechanged;
    xmlhttp.open("get", url, true);
    xmlhttp.send(null);
}
function statechanged()
{
    if(xmlhttp.readystate==4)
    {
        document.getelementbyid("city").value = xmlhttp.responsetext;
    }
}
// --></script>
</head>
<body>
<form name="form1" action="" method="post">
    <label >city code:</label>
    <input type="text" name="code" onblur = "showmsg(this.value)" />
    <br></br>
    <label>city name:</label>
    <input type="text" name="city" id="city" ></input>
</form>
</body>
</html>

response.jsp
复制代码 代码如下:

<%@ page language="java" contenttype="text/plain; charset=utf-8"
pageencoding="utf-8"%>
<%@ page import="com.lwf.eus.util.*,java.util.*,com.lwf.eus.entity.*,com.lwf.eus.bean.*" %>
<%
string code = request.getparameter("q");
system.out.println(code);
if(code.equals("140"))
    out.print("上海");
else if(code.equals("150"))
    out.print("北京");
else if(code.equals("160"))
    out.print("天津");
else
    out.print("未知地");
%>

这里要注意的是由于返回的结果要在文本框中显示,因此在response.jsp中没有<html>等标签,因为测试发现如果有这些标签的话,在cityname文本框中这些标签也会显示。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网