jQuery - 9.Ajax

时间:2021-07-14 06:03:45

9.1 Ajax 的 XMLHttpRequest 对象

9.2 JQuery中的Ajax

9.2.1 load()方法

9.2.2 $.get()

9.2.3 $.post()

9.2.4 $.getScript()方法和$.getJson()方法

9.2.5 序列化元素

1.serialize()   序列表表格内容为字符串

2.serializeArray()   序列化表格元素 (类似 '.serialize()' 方法) 返回 JSON 数据结构数据。

3.$.param()   用来对一个数组或者对象按key\value进行序列化

9.2.6 Jquery中的Ajax全局事件:  ajaxStart(callback),ajaxStop(callback)

9.2.7 $.ajax

9.1 Ajax 的 XMLHttpRequest 对象

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
var xmlHttpReq = null;
function Ajax() {
if (window.ActiveXObject) {//ie5,ie6是ActiveObject的方式
xmlHttpReq = new ActiveXObject("Microsft.XMLHTTP");
} else if (window.XMLHttpRequest) {//除ie5,ie6以外的浏览器,XHR是window的子对象
xmlHttpReq = new XMLHttpRequest();
}
//xtr是通过open方法来初始化
//open( method 请求的动作类型 , url 地址 , async 同步还是异步)
xmlHttpReq.open("GET", "index.html", true);
xmlHttpReq.onreadystatechange = RequestCallBack;//设置回调函数
xmlHttpReq.send(null);//因为get方法提交,可以使用null作为参数调用 function RequestCallBack() {//一旦readyState值改变就调用该函数
if (xmlHttpReq.readyState == 4) {
if (xmlHttpReq.status == 200) {
//讲xmlHttpReq.responseText的值赋予id 为resText的元素
document.getElementById('resText').innerHTML = xmlHttpReq.responseText;
}
}
}
}
</script>
</head>
<body>
<input type="button" value="Ajax提交" onclick="Ajax()" />
<div id="resText"></div>
</body>
</html>

jQuery - 9.Ajax

9.2 JQuery中的Ajax

9.2.1 load()方法

load(url, [data], [callback])

url:待装入 HTML 网页网址。

data(可选):发送至服务器的 key/value 数据。在jQuery 1.3中也可以接受一个字符串了。

callback(可选):载入成功时回调函数。

9.2.2 $.get()

url,[data],[callback],[type]

url:待载入页面的URL地址

data:待发送 Key/value 参数。

callback:载入成功时回调函数。

type:返回内容格式,xml, html, script, json, text, _default

案例:

以返回数据为json为例

test.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function () {
$("#send").click(function () {
$.get('Ajax_get.ashx',
{
username: $('#username').val(),
content: $('#content').val()
}
//$("#form1").serialize() //序列化表格元素
, function (data, textStatus) {
var username = data.username; //取返回数据的username
console.info(username);
$('#resText').html(username);
}, "json");//格式选择json
});
})
</script>
</head>
<body>
<form id="form1" action="#">
<p>评论</p>
<p>姓名:<input type="text" name="username" id="username" /></p>
<p>内容:<textarea name="content" id="content" rows="2" cols="20">content</textarea></p>
<p>
<input type="button" id="send" value="提交" />
</p>
</form>
<div class="comment">已有评论.</div>
<div id="resText"></div>
</body>
</html>

Ajax_get.ashx

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; //引用的newtonsoft.json.dll (json.net) namespace EasyUiTest.Ajax_get
{
/// <summary>
/// Ajax_get 的摘要说明
/// </summary>
public class Ajax_get : IHttpHandler
{
HttpRequest Request;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string username = context.Request["username"].ToString();
string content = context.Request["content"].ToString(); //linq to json
JObject json = new JObject();
json.Add(new JProperty("username", username));
json.Add(new JProperty("content", content)); context.Response.Write(json);
} public bool IsReusable
{
get
{
return false;
}
}
}
}

jQuery - 9.Ajax

9.2.3 $.post()

它与$.get()使用方法和结构一样,他们之间的区别我就不说了。自己去研究。

9.2.4 $.getScript()方法和$.getJson()方法

$.getScript()加载js文件

$.getScript(‘test.js’)

$.getJson()用来加载json文件

$.getJson(‘test.json’)

9.2.5 序列化元素

1.serialize()

序列表表格内容为字符串。

$("#form1").serialize() //序列化表格里所有元素,取代 { username: $('#username').val(),…}

$.get('Ajax_get.ashx',
                        //{

//  username: $('#username').val(),

//   content: $('#content').val()

// }

$("#form1").serialize() //序列化表格里所有元素

, function (data, textStatus) {…}, "json");//格式选择json

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function () {
$("#send").click(function () {
var $data = $(":checkbox,:radio").serialize();
console.info($data);
})
})
</script>
</head>
<body>
<input type="checkbox" name="check" value="1" checked />篮球<br />
<input type="checkbox" name="check" value="2" />足球<br />
<input type="checkbox" name="check" value="3" />乒乓球<br />
<input type="checkbox" name="check" value="4" />羽毛球<br /> <input type="radio" name="radio" value="1" checked />篮球<br />
<input type="radio" name="radio" value="2" />足球<br />
<input type="radio" name="radio" value="3" />乒乓球<br />
<input type="radio" name="radio" value="4" />羽毛球<br /> <button id="send">提交</button>
</body>
</html>

jQuery - 9.Ajax

2.serializeArray()

序列化表格元素 (类似 '.serialize()' 方法) 返回 JSON 数据结构数据。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- 引入jQuery -->
<script src="../Scripts/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function () {
var fields = $("select,:checkbox,:radio").serializeArray();
console.log(fields);
$.each(fields, function (i, field) {
$("#results").append(field.value + " , ");
});
})
</script> <p id="results"><b>结果:</b> </p> <input type="checkbox" name="check" value="1" checked/>篮球<br/>
<input type="checkbox" name="check" value="2" checked/>足球<br/>
<input type="checkbox" name="check" value="3" checked/>乒乓球<br/>
<input type="checkbox" name="check" value="4" />羽毛球<br/> <input type="radio" name="radio" value="1" checked/>篮球<br/>
<input type="radio" name="radio" value="2" />足球<br/>
<input type="radio" name="radio" value="3" />乒乓球<br/>
<input type="radio" name="radio" value="4" />羽毛球<br/>

jQuery - 9.Ajax

3.$.param()

将表单元素数组或者对象序列化。是.serialize()的核心方法。

<script type="text/javascript">
//<![CDATA[
$(function(){
var obj={a:1,b:2,c:3};
var k = $.param(obj);
alert(k) // 输出 a=1&b=2&c=3
})
//]]>
</script>

9.2.6 Jquery中的Ajax全局事件

ajaxStart(callback) AJAX 请求开始时执行函数。Ajax 事件。

ajaxStop(callback) AJAX 请求结束时执行函数。Ajax 事件。

$("#loading").ajaxStart(function(){

$(this).show();

});

9.2.7 $.ajax

jQuery.ajax(url,[settings])
url:一个用来包含发送请求的URL字符串。

settings:AJAX 请求设置。所有选项都是可选的。

回调函数

如果要处理$.ajax()得到的数据,则需要使用回调函数。beforeSend、error、dataFilter、success、complete。

  • beforeSend 在发送请求之前调用,并且传入一个XMLHttpRequest作为参数。
  • error 在请求出错时调用。传入XMLHttpRequest对象,描述错误类型的字符串以及一个异常对象(如果有的话)
  • dataFilter 在请求成功之后调用。传入返回的数据以及"dataType"参数的值。并且必须返回新的数据(可能是处理过的)传递给success回调函数。
  • success 当请求之后调用。传入返回后的数据,以及包含成功代码的字符串。
  • complete 当请求完成之后调用这个函数,无论成功或失败。传入XMLHttpRequest对象,以及一个包含成功或错误代码的字符串。

1.代替$.getScript()方法:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
* { margin:0; padding:0;}
body { font-size:12px;}
.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
.comment h6 { font-weight:700; font-size:14px;}
.para { margin-top:5px; text-indent:2em;background:#DDD;}
</style>
<!-- 引入jQuery -->
<script src="../Scripts/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
<script>
$(function () {
$('#send').click(function () {
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
});
})
</script>
</head>
<body>
<br/>
<p>
<input type="button" id="send" value="加载"/>
</p> <div class="comment">已有评论:</div>
<div id="resText" > </div> </body>
</html>

test.js

var comments = [
{
"username": "张三",
"content": "沙发."
},
{
"username": "李四",
"content": "板凳."
},
{
"username": "王五",
"content": "地板."
}
]; var html = '';
$.each( comments , function(commentIndex, comment) {
html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
}) $('#resText').html(html);

jQuery - 9.Ajax

2.代替$.getJSON()方法

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
* { margin:0; padding:0;}
body { font-size:12px;}
.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
.comment h6 { font-weight:700; font-size:14px;}
.para { margin-top:5px; text-indent:2em;background:#DDD;}
</style>
<script src="../Scripts/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
<!-- 引入jQuery --> <script>
$(function () {
$('#send').click(function () {
$.ajax({
type: "GET",
url: "test.aspx",
dataType: "json",
success: function (data) {
$('#resText').empty();
var html = '';
$.each(data, function (commentIndex, comment) {
html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
})
$('#resText').html(html);
}
});
});
})
</script>
</head>
<body>
<br/>
<p>
<input type="button" id="send" value="加载"/>
</p> <div class="comment">已有评论:</div>
<div id="resText" > </div> </body>
</html>

test.aspx

[
{
"username": "张三",
"content": "沙发."
},
{
"username": "李四",
"content": "板凳."
},
{
"username": "王五",
"content": "地板."
}
]

效果同上。