jQuery Ajax 方法调用 Asp.Net WebService 的详细例子[转]

转载出处:http://hi.baidu.com/gisland/blog/item/0f592538631c7a2eb8998fec.html

原代码无法正常运行,以下是删除result.d的代码

1.JQ_WebService.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQ_WebService.aspx.cs" Inherits="JQ_WebService" %>

<!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>jQuery.Ajax调用Aspx.Net WebService </title>

    
<script src="javascript/jquery-1.3.2.js" type="text/javascript" language="javascript"></script>

    
<style type="text/css">
        .hover
        
{
            cursor
: pointer; 
            background
: #ffc; 
        
}
        .button
        
{
            width
: 150px;
            float
: left;
            text-align
: center;
            margin
: 10px;
            padding
: 10px;
            border
: 1px solid #888;
        
}
        #dictionary
        
{
            text-align
: center;
            font-size
: 18px;
            clear
: both;
            border-top
: 3px solid #888;
        
}
        #loading
        
{
            border
: 1px #000 solid;
            padding
: 20px;
            margin
: 0 auto;
            position
: absolute;
            display
: none;
        
}
        #switcher
        
{
        
}
    
</style>
    
<script type="text/javascript">

        
//无参数调用
        $(document).ready(function() {
            $(
'#btn1').click(function() {
                $.ajax({
                    type: 
"POST",   //访问WebService使用Post方式请求
                    contentType: "application/json"//WebService 会返回Json类型  -----设置此项contentType后data为"{}"否则为"" -----
                    url: "JQ_WebService.asmx/HelloWorld"//调用WebService的地址和方法名称组合 ---- WsURL/方法名
                    data: "{}",         //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到       
                    dataType: "json",
                    success: 
function(result) {     //回调函数,result,返回值
                        $('#dictionary').append(result);
                    }
                });
            });
        });

        
//有参数调用
        $(document).ready(function() {
            $(
"#btn2").click(function() {
                $.ajax({
                    type: 
"POST",
                    contentType: 
"application/json",
                    url: 
"JQ_WebService.asmx/GetWish",
                    data: 
"{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
                    dataType: 
'json',
                    success: 
function(result) {
                        $(
'#dictionary').append(result);
                    }
                });
            });
        });
        
        
        
//返回集合(引用自网络,很说明问题)
        $(document).ready(function() {
            $(
"#btn3").click(function() {
                $.ajax({
                    type: 
"POST",
                    contentType: 
"application/json",
                    url: 
"JQ_WebService.asmx/GetArray",
                    data: 
"{i:10}",
                    dataType: 
'json',
                    success: 
function(result) {
                        $(result).each(
function() {
                            $(
'#dictionary').append(this.toString() + " ");
                            
//alert(result.d.join(" | "));
                        });
                    }
                });
            });
        });

        
//返回复合类型
        $(document).ready(function() {
            $(
'#btn4').click(function() {
                $.ajax({
                    type: 
"POST",
                    url: 
"JQ_WebService.asmx/GetClass",
                    data: 
"",
                    dataType: 
'json',
                    
//使用beforeSend设置在data不为"{}"的情况下使用,type:"GET"方式也需要设置
                    beforeSend: function(x) {
                        x.setRequestHeader(
"Content-Type""application/json; charset=utf-8");
                         }, 
                    success: 
function(result) {
                        $(result).each(
function() {
                            
//alert(this);
                            $('#dictionary').append(this['ID'+ " " + this['Value']);
                            
//alert(result.d.join(" | "));
                        });

                    }
                });
            });
        });

        
//返回DataSet(XML)
        $(document).ready(function() {
            $(
'#btn5').click(function() {
                $.ajax({
                    type: 
"POST",
                    url: 
"JQ_WebService.asmx/GetDataSet",
                    data: 
"",
                    dataType: 
'xml'//返回的类型为XML ,和前面的Json,不一样了
                    success: function(result) {
                    
//演示一下捕获
                        try {   
                            $(result).find(
"Table1").each(function() {
                                $(
'#dictionary').append($(this).find("ID").text()
                                   
+ " " + $(this).find("Value").text());
                            });
                        }
                        
catch (e) {
                            alert(e);
                            
return;
                        }
                    },
                    error: 
function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
                        if (status == 'error') {
                            alert(status);
                        }
                    }
                });
            });
        });

        
//Ajax 为用户提供反馈,利用ajaxStart和ajaxStop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jQuery对象在Ajax前后回调
        //但对与Ajax的监控,本身是全局性的
        $(document).ready(function() {
            $(
'#loading').ajaxStart(function() {
                $(
this).show();
            }).ajaxStop(
function() {
                $(
this).hide();
            });
        });

        
// 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
        $(document).ready(function() {
            $(
'div.button').hover(function() {
                $(
this).addClass('hover');
            }, 
function() {
                $(
this).removeClass('hover');
            });
        });
        
        
    
</script>

</head>
<body>
    
<form id="form1" runat="server">
        
<div id="switcher">
        
<h2>
            jQuery 的WebServices 调用
</h2>
        
<div class="button" id="btn1">
            HelloWorld
</div>
        
<div class="button" id="btn2">
            传入参数
</div>
        
<div class="button" id="btn3">
            返回集合
</div>
        
<div class="button" id="btn4">
            返回复合类型
</div>
        
<div class="button" id="btn5">
            返回DataSet(XML)
</div>
    
</div>
    
<div id="loading">
        
<img src="images/ajax-loader.gif" alt="" />
    
</div>
    
<div id="dictionary">
    
</div>

    
</form>
</body>
</html>

2.JQ_WebService.asmx代码

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
//using System.Linq;

/// <summary>
/// JQ_WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(
false)]
/*  
 * 这个一般是安装了ASP.NET Ajax的组件, 
 * 从而可以在客户端使用JavaScript访问WebService, 
 * 而为了让Web服务支持此功能
*/
[System.Web.Script.Services.ScriptService]
public class JQ_WebService : System.Web.Services.WebService
{

    
public JQ_WebService()
    {

        
//如果使用设计的组件,请取消注释以下行 
        
//InitializeComponent(); 
    }

    [WebMethod]
    
public string HelloWorld()
    {

        
return "Hello World";
    }

    
/// <summary>
        
/// 带参数
        
/// </summary>
        
/// <param name="value1"></param>
        
/// <param name="value2"></param>
        
/// <param name="value3"></param>
        
/// <param name="value4"></param>
        
/// <returns></returns>
        [WebMethod]
        
public string GetWish(string value1, string value2, string value3, int value4)
        {
            
return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
        }

        
/// <summary>
        
/// 返回集合
        
/// </summary>
        
/// <param name="i"></param>
        
/// <returns></returns>
        [WebMethod]
        
public System.Collections.Generic.List<int> GetArray(int i)
        {
            System.Collections.Generic.List
<int> list = new System.Collections.Generic.List<int>();

            
while (i >= 0)
            {
                list.Add(i
--);
            }

            
return list;
        }

        
/// <summary>
        
/// 返回一个复合类型
        
/// </summary>
        
/// <returns></returns>
        [WebMethod]
        
public Class1 GetClass()
        {
            Class1 c
=new Class1();
            c.ID
="1";
            c.Value
="牛年大吉";
            
return c;
        }

        
/// <summary>
        
/// 返回XML
        
/// </summary>
        
/// <returns></returns>
        [WebMethod]
        
public DataSet GetDataSet()
        {
            DataSet ds 
= new DataSet();
            DataTable dt 
= new DataTable();
            dt.Columns.Add(
"ID", Type.GetType("System.String"));
            dt.Columns.Add(
"Value", Type.GetType("System.String"));
            DataRow dr 
= dt.NewRow();
            dr[
"ID"= "1";
            dr[
"Value"= "新年快乐";
            dt.Rows.Add(dr);
            dr 
= dt.NewRow();
            dr[
"ID"= "2";
            dr[
"Value"= "万事如意";
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);
            
return ds;
        }
    }
    
//自定义的类,只有两个属性
    public class Class1
    {
        
private string id;
        
private string val;

        
public string ID
        {
            
get { return id; }
            
set { id = value; }
        }
        
public string Value 
        {
            
get { return val; }
            
set { val=value;}
        }
    }




原文地址:https://www.cnblogs.com/hejunrex/p/1652133.html