使用JavaScript 动态生成image对象也可以产生http请求,进而通过查询字符串来向服务器提交数据,实现与服务器通信的目的,是ajax前的JavaScript通信方法. 但是这种通信是单向的,即只能向服务器发送数据,但无法返回结果.(源码下载地址:http://codechina.net/source/2001372)
<!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>
<title>无标题页</title>
<script type="text/javascript">
function sendRequest()
{
//实例化Image对象
var img=new Image();
var url="image.ashx?msg="+escape(form1.Text1.value);
//发生错误后处理函数
img.οnerrοr=onError;
//正确加载后处理函数
img.οnlοad=onLoad;
//向服务器发送请求
img.src=url;
}
function onError()
{
alert("Error!");
}
function onLoad()
{
alert("Success!");
}
</script>
</head>
<body>
<form id="form1">
<div>
<input id="Button1" type="button" value="button" οnclick="sendRequest();"/>
<input id="Text1" type="text" /></div>
<div id="imgdiv"></div>
</form>
</body>
</html>
服务器端代码(image.ashx):
<%@ WebHandler Language="C#" Class="image" %>
using System;
using System.Web;
public class image: IHttpHandler {
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
string msg = context.Request.QueryString[0];
//接收参数并处理,这里省略了处理代码
//
//context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}