javascript版本的ajax发送请求
(1)、创建XMLHttpRequest对象,这个对象就是ajax请求的核心,是ajax请求和响应的信息载体,单是不同浏览器创建方式不同
(2)、请求路径
(3)、使用open方法绑定发送请求
(4)、使用send() 方法发送请求
(5)、获取服务器返回的字符串 xmlhttpRequest.responseText;
(6)、获取服务端返回的值,以xml对象的形式存储 xmlhttpRequest.responseXML;
(7)、使用W3C DOM节点树方法和属性对该XML文档对象进行检查和解析。
序言:
近来随着项目的上线实施,稍微有点空闲,闲暇之时偶然发现之前写的关于javascript原生xmlHttp ajax方法以及后来jquery插件ajax方法,于是就行了一些总结,因时间原因,并未在所有浏览器上进行测试,目前测试的IE8,9,10,Google Chrome,Mozilla Firefox,Opera常用几款,如大家在进行验证测试发现有问题,请及时反馈与我,谢谢大家。
言归正传,直接上代码:
前端代码
<!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>Ajax练习</title> <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <style type="text/css"> label{width:50px;display:inline-block;} </style> </head> <body> <div id="contentDiv"> <h2 id="html-表单元素">html5表单元素</h2> <label>E-mail</label><input type="email" name="UserEmail" id="UserEmail" value="251608027@qq.com" /><br /> <label>URL:</label><input type="url" name="UserURL" id="UserURL" value="http://www.baidu.com" /><br /> <label>Number:</label><input type="number" name="UserNumber" id="UserNumber" min="1" max="100" value="87" /><br /> <label>Range:</label><input type="range" name="UserRange" min="1" max="100" value="78" /><br /> <label>Date:</label><input type="date" name="UserDate" id="UserDate" value="2015-12-01" /><br /> <label>Search:</label><input type="search" name="UserSearch" id="UserSearch" value="search" /><br /> <label id="lblMsg" style="color:Red; width:100%;"></label><br /> <input type="button" id="btnXmlHttp" value="提 交" onclick="return xmlPost();" /> <input type="button" id="btnAjax" value="Ajax提 交" onclick="return Ajax();" /> <input type="button" id="btnPost" value="Post提 交" onclick="return Post();" /> <input type="button" id="btnGet" value="Get提 交" onclick="return Get();" /> <input type="button" id="btnGetJSON" value="GetJSON提 交" onclick="return GetJSON();" /> <input type="button" id="btnCustom" value="Custom提 交" onclick="return Custom();" /> <br /><label id="lblAD" style="color:Red; width:100%;">.NET技术交流群:70895254,欢迎大家</label> <script type="text/javascript"> //基础数据 var jsonData = { UserEmail: $("#UserEmail").val(), UserURL: $("#UserURL").val(), UserNumber: $("#UserNumber").val(), UserRange: $("#UserRange").val(), UserDate: $("#UserDate").val(), UserSearch: $("#UserSearch").val() }; //统一返回结果处理 function Data(data, type) { if (data && data.length > 0) { var lblMsg = ""; for (i = 0; i < data.length; i++) { for (var j in data[i]) { lblMsg += j + ":" + data[i][j]; if (j != "Name" && j != "UserSearch") { lblMsg += "," } } if (i != data.length) { lblMsg += ";"; } } $("#lblMsg").html(type + "请求成功,返回结果:" + lblMsg); } } </script> <script type="text/javascript"> //javascript 原生ajax方法 function createXMLHttp() { var XmlHttp; if (window.ActiveXObject) { var arr = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"]; for (var i = 0; i < arr.length; i++) { try { XmlHttp = new ActiveXObject(arr[i]); return XmlHttp; } catch (error) { } } } else { try { XmlHttp = new XMLHttpRequest(); return XmlHttp; } catch (otherError) { } } } function xmlPost() { var xmlHttp = createXMLHttp(); var queryStr = "Ajax_Type=Email&jsonData=" + JSON.stringify(jsonData); var url = "/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(); xmlHttp.open('Post', url, true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send(queryStr); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var data = eval(xmlHttp.responseText); Data(data, "javascript原生xmlHttp"); } } } </script> <script type="text/javascript"> //jquery $.ajax方法 function Ajax() { $.ajax({ url: "/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(), type: "Post", async: false, data: { Ajax_Type: "Email", jsonData: JSON.stringify(jsonData) }, dataType: "json", beforeSend: function () { //发送请求前 $("#btnPost").attr('disabled', "true"); }, complete: function () { //发送请求完成后 $("#btnPost").removeAttr("disabled"); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("error!" + errorThrown); //alert("请求错误,请重试!"); }, success: function (data) { Data(data, "Jquery $.ajax"); } }); } //jquery $.post方法 function Post() { $.post("/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(), { Ajax_Type: "Email", jsonData: JSON.stringify(jsonData) }, function (data) { Data(data, "Jquery $.post"); } ); } //jquery $.getJSON方法 function GetJSON() { $.getJSON("/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(), { Ajax_Type: "Email", jsonData: JSON.stringify(jsonData) }, function (data) { Data(data, "Jquery $.getJSON"); } ); } //jquery $.get方法 function Get() { $.get("/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(), { Ajax_Type: "Email", jsonData: JSON.stringify(jsonData) }, function (data) { Data(data, "Jquery $.get"); } ); } </script> <script type="text/javascript"> //javascript原生脚本自定义jquery $.ajax方法 var CustomAjax = function (custom) { // 初始化 var type = custom.type; //type参数,可选 var url = custom.url; //url参数,必填 var data = custom.data; //data参数可选,只有在post请求时需要 var dataType = custom.dataType; //datatype参数可选 var success = custom.success; //回调函数可选 var beforeSend = custom.beforeSend; //回调函数可选 var complete = custom.complete; //回调函数可选 var error = custom.error; //回调函数可选 if (type == null) {//type参数可选,默认为get type = "get"; } if (dataType == null) {//dataType参数可选,默认为text dataType = "text"; } var xmlHttp = createXMLHttp(); // 创建ajax引擎对象 xmlHttp.open(type, url, true); // 打开 // 发送 if (type == "GET" || type == "get" || type == "Get") {//大小写 xmlHttp.send(null); } else if (type == "POST" || type == "post" || type == "Post") { xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xmlHttp.send(data); } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { if (dataType == "text" || dataType == "TEXT") { if (success != null) { //普通文本 success(xmlHttp.responseText); } } else if (dataType == "xml" || dataType == "XML") { if (success != null) { //接收xml文档 success(xmlHttp.responseXML); } } else if (dataType == "json" || dataType == "JSON") { if (success != null) { //将json字符串转换为js对象 success(eval("(" + xmlHttp.responseText + ")")); } } } }; }; //自定义方法 function Custom() { CustomAjax({ type: "Post", url: "/Handler/AjaxHandlerHelper.ashx?no.=" + Math.random(), data: "Ajax_Type=Email&jsonData=" + JSON.stringify(jsonData), dataType: "json", success: function (data) { Data(data, "Custom自定义"); } }); } </script> </div> </body> </html>
.ashx后端代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; namespace WebHTML5.Handler { /// <summary> /// AjaxHandlerHelper 的摘要说明 /// </summary> public class AjaxHandlerHelper : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; //context.Response.Charset = "utf-8"; var Ajax_Type = context.Request.QueryString["Ajax_Type"] == null ? context.Request.Form["Ajax_Type"] : context.Request.QueryString["Ajax_Type"]; switch (Ajax_Type) { case "Email": context.Response.Write(PostEmail(context)); break; default: context.Response.Write("[{\"Age\":28,\"Name\":\"张鹏飞\"}]"); break; } } public static string PostEmail(HttpContext context) { string semail = string.Empty; if (context.Request.HttpMethod == "GET") { semail = "[" + context.Request.QueryString["jsonData"] + "]"; } else { semail = "[" + context.Request.Form["jsonData"] + "]"; } return semail; } /// <summary> /// JSON序列化 /// </summary> public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// <summary> /// JSON反序列化 /// </summary> public static T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } public bool IsReusable { get { return false; } } } }
Jquery 方法扩展
关于Jquery的方法扩展大家自行google或百度;
结束语
说明一下情况:案例中出现的html5 range标签的取值问题,写的不对,大家不要在意这些,关于range标签如何取值大家自行google或百度;

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

10款趣味横生的jQuery游戏插件,让您的网站更具吸引力,提升用户粘性!虽然Flash仍然是开发休闲网页游戏的最佳软件,但jQuery也能创造出令人惊喜的效果,虽然无法与纯动作Flash游戏媲美,但在某些情况下,您也能在浏览器中获得意想不到的乐趣。 jQuery井字棋游戏 游戏编程的“Hello world”,现在有了jQuery版本。 源码 jQuery疯狂填词游戏 这是一个填空游戏,由于不知道单词的上下文,可能会产生一些古怪的结果。 源码 jQuery扫雷游戏

本教程演示了如何使用jQuery创建迷人的视差背景效果。 我们将构建一个带有分层图像的标题横幅,从而创造出令人惊叹的视觉深度。 更新的插件可与JQuery 1.6.4及更高版本一起使用。 下载

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

Matter.js是一个用JavaScript编写的2D刚体物理引擎。此库可以帮助您轻松地在浏览器中模拟2D物理。它提供了许多功能,例如创建刚体并为其分配质量、面积或密度等物理属性的能力。您还可以模拟不同类型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流浏览器。此外,它也适用于移动设备,因为它可以检测触摸并具有响应能力。所有这些功能都使其值得您投入时间学习如何使用该引擎,因为这样您就可以轻松创建基于物理的2D游戏或模拟。在本教程中,我将介绍此库的基础知识,包括其安装和用法,并提供一

本文演示了如何使用jQuery和ajax自动每5秒自动刷新DIV的内容。 该示例从RSS提要中获取并显示了最新的博客文章以及最后的刷新时间戳。 加载图像是选择


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6
视觉化网页开发工具

WebStorm Mac版
好用的JavaScript开发工具