《锋利的jQuery》之jQuery与Ajax

jQuery对Ajax操作进行了封装,在jQuery中$.ajax()方法属于最底层的方法,第2层是load()、$.get()、$.post()方法,第3层是$.getScript()和$.getJSON()方法。

1. load()

载入远程HTML代码并插入DOM中。

无参数传递则是GET方式

$("#send").click(function() {

$("#resText").load("test.html");

}

有参数则是POST方式

$("#resText").load("test.php", {name: "rain", age: "22"}, function() {

// ...

});

回调函数:

load()方法中,无论Ajax请求是否成功,只要当请求完成,回调函数就被触发。

对应$.ajax()方法中的complete回调函数。

$("#resText").load("test.html",

functiion(responseText, // 请求返回的内容

textStatus, // 请求状态:success, error, notmodified, timeout

XMLHttpRequest // XMLHttpRequest对象

) {

// ...

});

load()通常用来从Web服务器上获取静态的数据文件,如果需要传递一些参数给服务器中的页面,可以使用$.get()或者$.post()。这两个是全局函数。load()是jQuery对象的方法。

2. $.get()

callback函数只在返回成功时执行

$("#send”).click(function() {

$.get("get1.php", {

username: $("#username").val(),

content: $("#content").val()

}, function(data, textStatus) {

$("resText").html(data);

}

);

处理JSON消息

$.get("get3.php", {

username: $("#username").val(),

content: $("#content").val()

}, function(data, textStatus) {

var username = data.username;

var content = data.content;

var txtHtml = "<div class='comment'><h6>"+

username+":</h6><p class='para'>"+

content+"</p></div>";

$("#resText").html(txtHtml);

}, "json");

3. $.post()

$("#send").click(function() {

$.post("post1.php", {

username: $("#username").val(),

content: $("#content").val()

}, function(data, textStatus) {

$("#resText").append(data);

});

});

4. $.getScript()

在页面初次加载时就取得所需的全部JavaScript文件是完全没有必要的。

$('#send').click(function() {

$.getScript('test.js');

});

$.getScript()直接加载.js文件,并且JavaScript文件会自动执行。

5. $.getJSON()

JSONP(JSON with Padding):是一种可以绕过同源策略的方法,即通过使用JSON与<script>标记相结合的方法,从服务器端直接返回可执行的JavaScript函数调用或者JavaScript对象。

$('#send').click(function() {

$.getJSON("http://api.flickr.com/...",

function(data) {

$.each(data.items, function(i, items) {

$("<img class='para'/>").attr("src", item.media.m).appendTo("#resText");

if (i == 3) {

return false;

}

}

}

});

6. $.ajax()

$.ajax()是jQuery最底层的Ajax实现。

7. serialize()

serialize()方法用于一个jQuery对象,能够将DOM元素内容序列化为字符串,用于Ajax请求。

$.get("get1.php", $("#form1").serialize(), function(data, textStatus) {

$("resText").html(data);

});

$(":checkbox, :radio").serialize(); 还会自动编码

serializeArray

8. Ajax和jQuery的聊天室小例子

8.1 客户端处理

(1)POST方式向服务器发送请求,解析服务器端返回的XML格式响应消息。

(2)浏览器每隔一定时间更新数据

HTML页面:

<h3>及时消息</h3>

<div , Helvetica, Arial, sans-serif'> <p , Helvetica, Arial, sans-serif'> <span , Helvetica, Arial, sans-serif'> </p>

<form , Helvetica, Arial, sans-serif'> <input type="text" , Helvetica, Arial, sans-serif'> <input type="submit" value="发送"/><br/>

</form>

</div>