您的位置:首页 > 其它

根据列表框的改变图象动态变化的AJAX实现例子

2007-11-17 21:30 561 查看
在做留言本的过程中,在注册的时候因为用到了随机生成动态验证码,所以在下面一个用户选择图象的过程中,就会有刷新一次验证码,很是麻烦,就想到了用AJAX实现局部刷新。(其实用javascript就一句话就可以实现)

<form name="form1" method="post">
<select name=select1 class="INPUT" onchange="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" onchange="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;
}
}

}

总算把这个给实现了,花了好久的时间。JAVASCRIPT如果出了什么错误真的很难发现的,大家小心点!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐