更新時(shí)間:2022-03-14 10:02:52 來源:動力節(jié)點(diǎn) 瀏覽1314次
ajax即異步JavaScript和XML(Asynchronous JavaScript and XML)。
簡短地說,在不重載整個(gè)網(wǎng)頁的情況下,AJAX通過后臺加載數(shù)據(jù),并在網(wǎng)頁上進(jìn)行顯示。
使用AJAX的應(yīng)用程序案例:谷歌地圖、騰訊微博、優(yōu)酷視頻、人人網(wǎng)等等。
通過 jQuery AJAX 方法,您能夠使用 HTTP Get 和 HTTP Post 從遠(yuǎn)程服務(wù)器上請求文本、HTML、XML 或 JSON 同時(shí)您能夠把這些外部數(shù)據(jù)直接載入網(wǎng)頁的被選元素中。
前面已經(jīng)提過ajax的方法,這節(jié)主要記錄針對ajax返回的數(shù)據(jù)處理方式。
由于服務(wù)端返回?cái)?shù)據(jù)格式為html,因此并不需要特殊處理就可以直接加載到我們的主頁面中。
$(function(){
$("#get").click(function(){
$.get("index.php",{username:$("#user").val(),
password:$("#password").val()},
function(data,textStatus){
$("#get").html(data)
})
})
})
xml格式的數(shù)據(jù)需要經(jīng)過處理,鑒于jquery強(qiáng)大的dom處理能力,處理xml文檔也可以使用常規(guī)的attr(),find(),filter()以及其他方法。
<?xml version="1.0" encoding="UTF-8"?>
<stulist>
<student email="[email protected]">
<name>zhangsan</name>
<id>1</id>
</student>
<student email="[email protected]">
<name>lisi</name>
<id>2</id>
</student>
</stulist>
$.ajax({
url:'ajax.asp',
type: 'GET',
dataType: 'xml',//這里可以不寫,但千萬別寫text或者h(yuǎn)tml!!!
timeout: 1000,
error: function(xml){
alert('Error loading XML document'+xml);
},
success: function(xml){
$(xml).find("student").each(function(i){
var id=$(this).children("id"); //取對象
var idvalue=$(this).children("id").text(); //取文本
alert(id_value);//這里就是ID的值了。
alert($(this).attr("email")); //這里能顯示student下的email屬性。
//最后么輸出了,這個(gè)是cssrain的寫法,貌似比macnie更JQ一點(diǎn)
$('<li></li>')
.html(id_value)
.appendTo('ol');
});
}
});
json數(shù)據(jù)是一種經(jīng)型的實(shí)時(shí)數(shù)據(jù)交互的數(shù)據(jù)存儲方法,JSON 是存儲和交換文本信息的語法。類似 XML。JSON 比 XML 更小、更快,更易解析。
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
var employees = [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName": "Carter" }
];
可以這樣訪問:
(1)如果為字符串格式:
如var arr = '{"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"u71d5u5b50"}}';//u71d5u5b50這個(gè)是php中自動轉(zhuǎn)換的
var dataObj = eval("("+arr+")");//只能死記硬背
$.each(dataObj,function(idx,item){
//輸出
alert(item.id+"哈哈"+item.name);
})
(2)如果為對象格式
var arr = {"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"u71d5u5b50"}};
$.each(arr,function(idx,item){
//輸出
alert(item.id+"哈哈"+item.name);
})
應(yīng)用實(shí)例:
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
type:"GET",
url:"music.txt",
dataType:"json",
success:function(data){
var music="<ul>";
//i表示在data中的索引位置,n表示包含的信息的對象
$.each(data,function(i,n){
//獲取對象中屬性為optionsValue的值
music+="<li>"+n["optionValue"]+"</li>";
});
music+="</ul>";
$('#result').append(music);
}
});
return false;
});
});
通過上述介紹相信大家對Ajax返回?cái)?shù)據(jù)的解析已經(jīng)有所了解,大家如果想了解更多相關(guān)知識,可以關(guān)注一下動力節(jié)點(diǎn)的AJAX教程,里面的內(nèi)容更加詳細(xì)豐富,很適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家能夠有所幫助哦。
初級 202925
初級 203221
初級 202629
初級 203743