常常須要使用客戶端腳本調用net的WebService,比較經常使用的是在ScriptManager腳本管理器的環境下使用回調調用WebService的方法,但是這些必須在aspx的頁面中進行,不免有些限制。ajax
jQuery庫是咱們比較經常使用的JavaScript庫,入門簡單,功能強大,對Ajax的支持比較友好。使用jQuery調用net的WebService也是常常遇到的。現將常見調用類型總結以下:json
一、環境app
jQuery 1.3.2ide
.net framework 2.0函數
Asp.net ajax 1.0測試
二、後臺WebService的代碼動畫
WebService中使用的實體類ui
三、前臺顯示頁面調用this
這裏前臺頁面使用htm頁面來進行測試。url
一、無參數調用
$(document).ready(function() {
$('#Button1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
contentType: "application/json", //WebService 會返回Json類型
url: "../WebService.asmx/HelloWorld", //調用WebService的地址和方法名稱組合---WsURL/方法名
data: "{}", //這裏是要傳遞的參數,格式爲 data: "{paraName:paraValue}",下面將會看到
dataType: 'json',
success: function(result) { //回調函數,result,返回值
alert(result.d);
}
});
});
});
二、帶參數的調用
$(document).ready(function() {
$('#Button1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
contentType: "application/json", //WebService 會返回Json類型
url: "../WebService.asmx/HelloWorld", //調用WebService的地址和方法名稱組合---WsURL/方法名
data: "{userName:'alpha'}",
dataType: 'json',
success: function(result) { //回調函數,result,返回值
alert(result.d);
}
});
});
});
三、返回複合類型
$(document).ready(function() {
$('#Button1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
contentType: "application/json", //WebService 會返回Json類型
url: "../WebService.asmx/GetClass", //調用WebService的地址和方法名稱組合---WsURL/方法名
data: "{}",
dataType: 'json',
success: function(result) { //回調函數,result,返回值
alert(result.d["StuName"]);
}
});
});
});
四、返回泛型集合
$(document).ready(function() {
$('#Button1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
contentType: "application/json", //WebService 會返回Json類型
url: "../WebService.asmx/GetList", //調用WebService的地址和方法名稱組合---WsURL/方法名
data: "{}",
dataType: 'json',
success: function(result) { //回調函數,result,返回值
$(result.d).each(function(){
$("#result").append(this["Id"]+" "+this["StuName"]+"<br />");
});
}
});
});
});
五、返回DataSet(xml格式)
$(document).ready(function() {
$('#Button1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
url: "../WebService.asmx/GetDataSet", //調用WebService的地址和方法名稱組合---WsURL/方法名
data: "{}",
dataType: "xml",
success: function(result) { //回調函數,result,返回值
$(result).find("Table1").each(function() {
$('#result').append($(this).find("Id").text() + " " + $(this).find("Name").text()+"<br />");
});
}
});
});
});
顯示動畫效果
$(document).ready(function(){
$('#loading').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
});
HTML代碼部分
<input id="Button1" type="button" value="Invoke" /> <div id="result"> <img id="loading" style="display: none;" alt="loading" src="../images/loading.gif" /> </div>