欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AJAX 自学练习 请求与显示

程序员文章站 2023-11-26 20:25:34
如下: request.jsp 复制代码 代码如下:<%@ page language="java" contenttype="text/html; charset=...
如下:
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文本框中这些标签也会显示。