在做留言本的过程中,在注册的时候因为用到了随机生成动态验证码,所以在下面一个用户选择图象的过程中,就会有刷新一次验证码,很是麻烦,就想到了用AJAX实现局部刷新。(其实用javascript就一句话就可以实现)
<form name="form1" method="post">
<select name=select1 class="INPUT" οnchange="showimage()">
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
</select>
</form>
<img src="online/pic/1.gif" name="abc" align="absmiddle">
<script>
function showimage()
{
document.images.abc.src="online/pic/"+document.form1.select1.options[document.form1.select1.selectedIndex].value+".gif";
}
</script>
下面是AJAX实现的
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type ="text/javascript">
var xmlhttp;
var result="";
function createXmlHttpRequest()
{
try
{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
catch(E)
{
xmlhttp=false;
}
}
if(!xmlhttp&&typeof XMLHttpRequest!='undefined')
{
try
{
xmlhttp=new XMLHttpRequest();
}
catch(_e)
{
xmlhttp=false;
}
}
}
//发送异步请求,这个是传送文本格式时候用的
function sendTextHttp(imgurl)
{
createXmlHttpRequest();
url="Handler.ashx?imgurl="+imgurl;
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=function(){callback()};
xmlhttp.send(null);
}
//回调函数
function callback()
{
if(xmlhttp.readyState==4)
if(xmlhttp.status==200)
{
result=xmlhttp.responseText;
document.images.img1.src=result;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="Select1" style="width: 104px; height: 47px" οnchange="sendTextHttp(this.value)">
<option value="01">图片1</option>
<option value="02">图片2</option>
<option value="03">图片3</option>
<option value="04">图片4</option>
<option value="05">图片5</option>
</select>
<img src="image/Icon_01.gif" style="width: 32px; height:32px" alt="图像" id="img1"/></div>
</form>
</body>
</html>
这里是handler.ashx服务器的处理文件
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
string aa = context.Request.QueryString["imgurl"];
if (aa != null)
{
string returnImageUrl = @"image/Icon_" + context.Request.QueryString["imgurl"] + ".gif";
context.Response.Write(returnImageUrl);
}
}
public bool IsReusable {
get {
return false;
}
}
}