JavaScript原生xmlHttp與jquery的ajax方法json數(shù)據(jù)格式實(shí)例
javascript版本的ajax發(fā)送請(qǐng)求
(1)、創(chuàng)建XMLHttpRequest對(duì)象,這個(gè)對(duì)象就是ajax請(qǐng)求的核心,是ajax請(qǐng)求和響應(yīng)的信息載體,單是不同瀏覽器創(chuàng)建方式不同
(2)、請(qǐng)求路徑
(3)、使用open方法綁定發(fā)送請(qǐng)求
(4)、使用send() 方法發(fā)送請(qǐng)求
(5)、獲取服務(wù)器返回的字符串 xmlhttpRequest.responseText;
(6)、獲取服務(wù)端返回的值,以xml對(duì)象的形式存儲(chǔ) xmlhttpRequest.responseXML;
(7)、使用W3C DOM節(jié)點(diǎn)樹方法和屬性對(duì)該XML文檔對(duì)象進(jìn)行檢查和解析。
序言:
近來隨著項(xiàng)目的上線實(shí)施,稍微有點(diǎn)空閑,閑暇之時(shí)偶然發(fā)現(xiàn)之前寫的關(guān)于javascript原生xmlHttp ajax方法以及后來jquery插件ajax方法,于是就行了一些總結(jié),因時(shí)間原因,并未在所有瀏覽器上進(jìn)行測(cè)試,目前測(cè)試的IE8,9,10,Google Chrome,Mozilla Firefox,Opera常用幾款,如大家在進(jìn)行驗(yàn)證測(cè)試發(fā)現(xiàn)有問題,請(qǐng)及時(shí)反饋與我,謝謝大家。
言歸正傳,直接上代碼:
前端代碼
<!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練習(xí)</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>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技術(shù)交流群:70895254,歡迎大家</label>
<script type="text/javascript">
//基礎(chǔ)數(shù)據(jù)
var jsonData = {
UserEmail: $("#UserEmail").val(),
UserURL: $("#UserURL").val(),
UserNumber: $("#UserNumber").val(),
UserRange: $("#UserRange").val(),
UserDate: $("#UserDate").val(),
UserSearch: $("#UserSearch").val()
};
//統(tǒng)一返回結(jié)果處理
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 + "請(qǐng)求成功,返回結(jié)果:" + 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 () { //發(fā)送請(qǐng)求前
$("#btnPost").attr('disabled', "true");
},
complete: function () { //發(fā)送請(qǐng)求完成后
$("#btnPost").removeAttr("disabled");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error!" + errorThrown);
//alert("請(qǐng)求錯(cuò)誤,請(qǐng)重試!");
},
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參數(shù),可選
var url = custom.url; //url參數(shù),必填
var data = custom.data; //data參數(shù)可選,只有在post請(qǐng)求時(shí)需要
var dataType = custom.dataType; //datatype參數(shù)可選
var success = custom.success; //回調(diào)函數(shù)可選
var beforeSend = custom.beforeSend; //回調(diào)函數(shù)可選
var complete = custom.complete; //回調(diào)函數(shù)可選
var error = custom.error; //回調(diào)函數(shù)可選
if (type == null) {//type參數(shù)可選,默認(rèn)為get
type = "get";
}
if (dataType == null) {//dataType參數(shù)可選,默認(rèn)為text
dataType = "text";
}
var xmlHttp = createXMLHttp(); // 創(chuàng)建ajax引擎對(duì)象
xmlHttp.open(type, url, true); // 打開
// 發(fā)送
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字符串轉(zhuǎn)換為js對(duì)象
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 方法擴(kuò)展
關(guān)于Jquery的方法擴(kuò)展大家自行g(shù)oogle或百度;
結(jié)束語
說明一下情況:案例中出現(xiàn)的html5 range標(biāo)簽的取值問題,寫的不對(duì),大家不要在意這些,關(guān)于range標(biāo)簽如何取值大家自行g(shù)oogle或百度;
- JQuery的ajax獲取數(shù)據(jù)后的處理總結(jié)(html,xml,json)
- Jquery Ajax學(xué)習(xí)實(shí)例 向頁面發(fā)出請(qǐng)求,返回XML格式數(shù)據(jù)
- jQuery+ajax讀取并解析XML文件的方法
- 通過AJAX的JS、JQuery兩種方式解析XML示例介紹
- 用JQuery 實(shí)現(xiàn)AJAX加載XML并解析的腳本
- jQuery 利用$.ajax 時(shí)獲取原生XMLHttpRequest 對(duì)象的方法
- JQuery Ajax通過Handler訪問外部XML數(shù)據(jù)的代碼
- Jquery Ajax解析XML數(shù)據(jù)(同步及異步調(diào)用)簡(jiǎn)單實(shí)例
- Jquery通過Ajax訪問XML數(shù)據(jù)的小例子
- jQuery基于Ajax實(shí)現(xiàn)讀取XML數(shù)據(jù)功能示例
相關(guān)文章
JavaScript canvas實(shí)現(xiàn)動(dòng)態(tài)點(diǎn)線效果
這篇文章主要為大家詳細(xì)介紹了JavaScript canvas實(shí)現(xiàn)動(dòng)態(tài)點(diǎn)線效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
2007/12/23更新創(chuàng)意無限,簡(jiǎn)單實(shí)用(javascript log)
在javascript開發(fā)過程中,如果總是使用alert的方式調(diào)試程序,在某些簡(jiǎn)單的程序中是可行的. 但是在通常的項(xiàng)目很復(fù)雜,這種方式已經(jīng)很難滿足,企業(yè)級(jí)開發(fā)的需要。2007-12-12
基于JavaScript實(shí)現(xiàn)手機(jī)短信按鈕倒計(jì)時(shí)(超簡(jiǎn)單)
在淘寶等購物網(wǎng)站,我們都會(huì)看到一個(gè)發(fā)送短信倒計(jì)時(shí)的按鈕,究竟是如何實(shí)現(xiàn)的呢?下面小編通過本篇文章給大家分享一段代碼關(guān)于js實(shí)現(xiàn)手機(jī)短信按鈕倒計(jì)時(shí),需要的朋友參考下2015-12-12
解析JavaScript中delete操作符不能刪除的對(duì)象
這篇文章主要是對(duì)JavaScript中delete操作符不能刪除的對(duì)象進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-12-12
前端CryptoJS加密、后端JAVA解密代碼實(shí)現(xiàn)參考
這篇文章主要介紹了前端CryptoJS加密、后端JAVA解密代碼實(shí)現(xiàn)參考,需要的朋友可以參考下2023-12-12
javascript通過class來獲取元素實(shí)現(xiàn)代碼
javascript獲取元素有很多的方法,本文簡(jiǎn)單的介紹下通過class獲取元素的實(shí)現(xiàn)代碼,感興趣的朋友可以參考下,希望本文知識(shí)點(diǎn)可以幫助到你2013-02-02
用javascript實(shí)現(xiàn)讀取txt文檔的腳本
用javascript實(shí)現(xiàn)讀取txt文檔的腳本...2007-07-07
BootstrapTable refresh 方法使用實(shí)例簡(jiǎn)單介紹
本文就bootstrapTable refresh 方法如何傳遞參數(shù)做簡(jiǎn)單舉例說明,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-02-02

