Ajax访问服务器的几种方式

今天,学习到了三种通过Ajax访问后台数据库的方式,前台是JavaScript+html,后台是一个handler(一般处理程序),对于原理上面的东西不做太多描述,在输入用户名后,进行用户名校正,本实例采用的是异步请求方式,就是将open的第三个参数设置为true,如果要采用同步的请求方式,改成false即可,就不需要onreadystatechange方法来进行监听

一、处理字符串或者html(GET)

前台

<!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">  
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var MSXML = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var n = 0; n < MSXML.length; n++) {
try {
xmlhttp = new ActiveXObject(MSXML[n]);
break;
} catch (e) { }
}
}
return xmlhttp;
}

    //使用Ajax的步骤,GET请求
function checkUserByAjaxByGet() {
var name = document.getElementById("name").value;

//第一步,得到一个XMLHttpRequest对象
//var xhr = new XMLHttpRequest();
//如果是IE,就需要使用ActiveX组件
//var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

var xhr = createXMLHttpRequest();
//第二步,建立一个连接请求,false表示同步执行,只有当服务器执行完成后才继续执行;true表示异步,无需等待服务器执行结果继续执行;常用方式为true(异步)
xhr.open("GET", "checkUserPostOrGetHandler.ashx?name=" + name, true);

//设置一个针对reandyonchange的事件的监听函数
xhr.onreadystatechange = function() {
//document.getElementById("statusMsg").innerHTML += "readyState:" + xhr.readyState + ",status" + xhr.status + "<br/>";
//readyState:0、代表未初始化,还没有调用open方法;1、代表正在加载。open方法已被调用,但send方法还没有被调用;2、代表已经加载完毕,send已被调用,请求已经开始;3、代表交互中,服务器正在发送响应;4、代表完成,响应发送完毕
//status:404、没找到页面(not found);403、禁止访问(forbidden);500、内部服务器出错(internal service error);200、一起正常(ok);304、没有被修改(not modified)(服务器返回304状态,表示源文件没有被修改
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
document.getElementById("msg").innerHTML = xhr.responseText;
}
}
}
//第三步,发起请求
xhr.send(null); 
}
 </script>
</head>
<body>
<form id="form1" runat="server" >

<p>
用户名:
  <input type="text" id="name" runat="server" οnchange="checkUserByAjaxByGet()"/>  
</p>
<div id="msg" ></div> 
<p>
密码:
<input type="password" id="pwd" />
</p>
</form>
<div id="statusMsg"></div>
</body>
</html>
后台:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace ExtjsApplication.Demo3
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class checkUserPostOrGetHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)

context.Response.ContentType = "text/plain";
string name = context.Request.Params["name"];
string msg = "恭喜您,该用户可用";
if ("admin".Equals(name)) { 
//实际应该调用后台数据库或者业务逻辑
msg = "对不起,用户已经存在";
}
context.Response.Write(msg);
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 

 

二、处理字符串或者html(POST)

前台

<!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">  
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var MSXML = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var n = 0; n < MSXML.length; n++) {
try {
xmlhttp = new ActiveXObject(MSXML[n]);
break;
} catch (e) { }
}
}
return xmlhttp;
}

 //使用Ajax的步骤,POST请求方式
function checkUserByAjaxByPost() {
var name = document.getElementById("name").value; 

//第一步,创建XHR对象
var xhr = createXMLHttpRequest();
//第二步,建立一个连接请求,false表示同步执行,只有当服务器执行完成后才继续执行;true表示异步,无需等待服务器执行结果继续执行;常用方式为true(异步)
xhr.open("POST", "checkUserPostOrGetHandler.ashx", true);

//第三步,设置一个针对reandyonchange的事件的监听函数,负责处理返回结果
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
var ret = xhr.responseText;
document.getElementById("msg").innerHTML = xhr.responseText;
if (ret == "对不起,用户已经存在") {
document.getElementById("name").focus();
}
}
}
}
//设置请求头,如果是post请求方式,必须设置,表示以表单形式发送文件,相当于form表单里面的enctype="application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//第四步,发起请求
xhr.send("name="+name+"&password=pppp");
}
 </script>
</head>
<body>
<form id="form1" runat="server" >

<p>
用户名:
  <input type="text" id="name" runat="server" οnchange="checkUserByAjaxByPost()"/>  
</p>
<div id="msg" ></div> 
<p>
密码:
<input type="password" id="pwd" />
</p>
</form>
<div id="statusMsg"></div>
</body>
</html>
后台:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace ExtjsApplication.Demo3
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class checkUserPostOrGetHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)

context.Response.ContentType = "text/plain";
string name = context.Request.Params["name"];
string msg = "恭喜您,该用户可用";
if ("admin".Equals(name)) { 
//实际应该调用后台数据库或者业务逻辑
msg = "对不起,用户已经存在";
}
context.Response.Write(msg);
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 

 

 

三、处理XML

前台

<!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">  
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var MSXML = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var n = 0; n < MSXML.length; n++) {
try {
xmlhttp = new ActiveXObject(MSXML[n]);
break;
} catch (e) { }
}
}
return xmlhttp;
}

//使用Ajax的步骤,XML访问服务器
function checkUserByAjaxByXML() {
var name = document.getElementById("name").value;

//第一步,创建XHR对象
var xhr = createXMLHttpRequest();
//第二步,建立一个连接请求,false表示同步执行,只有当服务器执行完成后才继续执行;true表示异步,无需等待服务器执行结果继续执行;常用方式为true(异步)
xhr.open("POST", "checkUserXMLHandler.ashx", true);

//第三步,设置一个针对reandyonchange的事件的监听函数,负责处理返回结果
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
var ret = xhr.responseXML;
var root = ret.documentElement;
var codeNode = root.getElementsByTagName("code")[0];
var MsgNode = root.getElementsByTagName("msg")[0];
//alert(root.getElementsByTagName("code")[0].nodeName);
//alert(root.firstChild.firstChild.nodeValue);
//alert(root.childNodes[0].childNodes[0].nodeValue);
//alert(ret.documentElement.nodeName); 
// alert(ret);
// document.getElementById("msg").innerHTML = xhr.responseXML;
// if (ret == "对不起,用户已经存在") {
// document.getElementById("name").focus();
// } 
document.getElementById("msg").innerHTML = MsgNode.firstChild.nodeValue;
if (codeNode.firstChild.nodeValue == "1") {
document.getElementById("name").focus();
}
}
}
}
//设置请求头,如果是post请求方式,必须设置,表示以表单形式发送文件,相当于form表单里面的enctype="application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//第四步,发起请求
xhr.send("name=" + name + "&password=pppp");
}
 </script>
</head>
<body>
<form id="form1" runat="server" >

<p>
用户名:
  <input type="text" id="name" runat="server" οnchange="checkUserByAjaxByXML()"/>  
</p>
<div id="msg" ></div> 
<p>
密码:
<input type="password" id="pwd" />
</p>
</form>
<div id="statusMsg"></div>
</body>
</html>
后台:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace ExtjsApplication.Demo3
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class checkUserPostOrGetHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)

context.Response.ContentType = "text/xml";
string name = context.Request.Params["name"];
string msg = "恭喜您,该用户可用";
int code = 0;
if ("admin".Equals(name))
{
//实际应该调用后台数据库或者业务逻辑
msg = "对不起,用户已经存在";
code = 1;
}
//context.Response.Write(msg);
context.Response.Write("<result><code>"+code+"</code><msg>"+msg+"</msg></result>");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 

 

 

四、处理JSON

前台

<!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">  
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var MSXML = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var n = 0; n < MSXML.length; n++) {
try {
xmlhttp = new ActiveXObject(MSXML[n]);
break;
} catch (e) { }
}
}
return xmlhttp;
}


//使用Ajax的步骤,JSON访问服务器
function checkUserByAjaxByJson() {
var name = document.getElementById("name").value;

//第一步,创建XHR对象
var xhr = createXMLHttpRequest();
//第二步,建立一个连接请求,false表示同步执行,只有当服务器执行完成后才继续执行;true表示异步,无需等待服务器执行结果继续执行;常用方式为true(异步)
xhr.open("POST", "checkUserJsonHandler.ashx", true);

//第三步,设置一个针对reandyonchange的事件的监听函数,负责处理返回结果
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
var ret = eval("(" + xhr.responseText + ")");
//alert(ret);
document.getElementById("msg").innerHTML = ret.msg; 
if (ret.code == "1") {
document.getElementById("name").focus();
}
}
}
}
//设置请求头,如果是post请求方式,必须设置,表示以表单形式发送文件,相当于form表单里面的enctype="application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//第四步,发起请求
xhr.send("name=" + name + "&password=pppp");
}

 </script>
</head>
<body>
<form id="form1" runat="server" >

<p>
用户名:
<input type="text" id="name" runat="server" οnchange="checkUserByAjaxByJson()"/>  
</p>
<div id="msg" ></div> 
<p>
密码:
<input type="password" id="pwd" />
</p>
</form>
<div id="statusMsg"></div>
</body>
</html>
后台:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace ExtjsApplication.Demo3
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class checkUserPostOrGetHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)

context.Response.ContentType = "text/json"; 
string name = context.Request.Params["name"];
string msg = "恭喜您,该用户可用";
int code = 0;
if ("admin".Equals(name))
{
//实际应该调用后台数据库或者业务逻辑
msg = "对不起,用户已经存在";
code = 1;
}
//context.Response.Write(msg);
//context.Response.Write("{code:'"+code+"',msg:'"+msg+"',obj:{name:'obj'}}");
context.Response.Write("{code:'" + code + "',msg:'" + msg + "'}");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值