日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

用JQuery中的Ajax方法获取web service等后台程序中的方法

發布時間:2023/11/30 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用JQuery中的Ajax方法获取web service等后台程序中的方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

                用JQuery中的Ajax方法獲取web service等后臺程序中的方法

1、準備需要被前臺html頁面調用的web Service,這里我們就用ws來代替了,代碼如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Threading;
using System.Xml;

namespace StudyJq.ws
{
??? /// <summary>
??? /// MyWebService 的摘要說明
??? /// </summary>
??? [WebService(Namespace = "http://tempuri.org/")]
??? [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
??? [System.ComponentModel.ToolboxItem(false)]
??? // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。
??? [System.Web.Script.Services.ScriptService]
??? public class MyWebService : System.Web.Services.WebService
??? {
??????? //無參數傳遞返回字符串
??????? [WebMethod]
??????? public string HelloWorld()
??????? {
??????????? Thread.Sleep(5000);
??????????? return "Hello World";
??????? }

??????? //有參傳遞,返回字符串
??????? [WebMethod]
??????? public string GetPersonInfo(string name,int age)
??????? {
??????????? string returnValue = string.Format("您的名字叫:{0},您的年齡是:{1},謝謝!",name,age.ToString());
??????????? return returnValue;
??????? }

??????? //返回一個集合
??????? [WebMethod]
??????? public List<int> GetArray(int i)
??????? {
??????????? List<int> list = new List<int>();
??????????? while (i >= 0)
??????????? {
??????????????? list.Add(i);
??????????????? i--;
??????????? }

??????????? return list;
??????? }

??????? //返回一個復雜的類型Person
??????? [WebMethod]
??????? public Person GetPerson(string name)
??????? {
??????????? Person p = new Person {Name=name,Age=18,School="北京大學" };

??????????? return p;
??????? }

??????? //返回一個DataSet對象(XML)并返回
??????? [WebMethod]
??????? //給返回DataSet傳遞參數的方法沒搞出來,一直報錯,有知道的請指教
??????? public DataSet GetDataSet()
??????? {
??????????? DataSet ds = new DataSet();
??????????? DataTable dt = new DataTable();
??????????? dt.TableName = "MyTable";
??????????? dt.Columns.Add("Id");
??????????? dt.Columns.Add("Name");
??????????? dt.Columns.Add("Age");
??????????? dt.Columns.Add("Address");

??????????? //添加數據到dt中
??????????? for (int i = 0; i < 3; i++)
??????????? {
??????????????? DataRow dr = dt.NewRow();
??????????????? dr["Id"] = i + 1;
??????????????? dr["Name"] = "張三" + i.ToString();
??????????????? dr["Age"] = 19 + i;
??????????????? dr["Address"] = "北京市朝陽區" + (i + 1).ToString();

??????????????? dt.Rows.Add(dr);
??????????? }

??????????? ds.Tables.Add(dt);
??????????? return ds;
??????? }


??????? //獲取后臺方法返回的XML格式的數據
??????? [WebMethod]
??????? public XmlDocument GetXml()
??????? {
??????????? string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Person><id>123</id><name>張三</name></Person>";
??????????? XmlDocument doc = new XmlDocument();
??????????? doc.LoadXml(xmlStr);
??????????? return doc ;
??????? }

??????? //獲取后臺方法返回的Json格式的數據
??????? [WebMethod]
??????? public string GetJsonData()
??????? {
??????????? //string strJson = "{\"Name\":\"李二\",\"Age\":\"99\"}";//單個
??????????? string strJson = "[{\"Name\":\"李二\",\"Age\":\"99\"},{\"Name\":\"王小六\",\"Age\":\"46\"}]";//json數組對象
??????????? return strJson;
??????? }
??????? //獲取指定路徑的Xml并返回
??????? [WebMethod]
??????? public XmlDocument ReadXml()
??????? {
??????????? //獲取文件的絕對路徑
??????????? string filePath = Server.MapPath("../xml/XmlTemp.xml");
??????????? XmlDocument doc = new XmlDocument();
??????????? doc.Load(filePath);
??????????? return doc;
??????? }

??? }

??? //自定義一個簡單的類
??? public class Person
??? {
??????? public string Name { get; set; }

??????? public int Age { get; set; }

??????? public string? School{get;set;}
??? }
}

2、前臺的HTML代碼如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
??? <title>Ajax調用Web Service方法</title>
??? <script src="js/jquery-1.9.0.min.js"></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;
??????????? background-color: #eee;
??????????? padding: 20px;
??????????? margin: 100px 0 0 200px;
??????????? position: absolute;
??????????? display:none;
??????? }
??? </style>
??? <script type="text/javascript">
??????? $(function () {
??????????? //獲取后臺方法返回的文本格式的字符串,無參數傳遞
??????????? $("#btnGetTextNoParam").click(function () {
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/HelloWorld",
??????????????????? type: "post",
??????????????????? dataType: "json",
??????????????????? data: "{}",
??????????????????? contentType: "application/json;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? $("#divContent").html(data.d);
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorMsg) {
??????????????????????? alert(errorMsg);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的文本格式的字符串,有參數參數傳遞
??????????? $("#btnGetTextParam").click(function () {
??????????????? //"{\"name\":\"aaa\"}"
??????????????? //將json對象轉換成json字符串對象
??????????????? var testData = JSON.stringify({"name":"張三","age":"24"});
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetPersonInfo",
??????????????????? type: "post",
??????????????????? data: testData,
??????????????????? dataType: "json",
??????????????????? contentType: "application/json;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? $("#divContent").html(data.d);
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的集合格式的數據
??????????? $("#btnGetList").click(function () {
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetArray",
??????????????????? type: "post",
??????????????????? data: "{\"i\":\"10\"}",
??????????????????? dataType: "json",
??????????????????? contentType: "application/json;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //集合對象得到的data是一個集合,所以只能通過遍歷的方式來訪問集合中的每一個變量
??????????????????????? var arr = new Array();
??????????????????????? $(data.d).each(function () {
??????????????????????????? arr[arr.length] = this.toString();
??????????????????????? });

??????????????????????? $("#divContent").html("你從后臺獲取到的集合對象的數據是:"+arr.join(","));
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回復合類型的變量
??????????? $("#btnGetClass").click(function () {
??????????????? var testData = JSON.stringify({"name":"李小明"});
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetPerson",
??????????????????? type: "post",
??????????????????? data: testData,
??????????????????? dataType: "json",
??????????????????? contentType: "application/json;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //復合類型的遍歷也需要用到each方法,來一個一個讀取類型中的字段的值
??????????????????????? $(data.d).each(function () {
??????????????????????????? $("#divContent").html("您讀取的Person對象的人的名字是:"+this["Name"]+",年齡是:"+this["Age"]+",畢業學校是:"+this["School"]);
??????????????????????? });
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的DataSet格式的數據
??????????? $("#btnGetDataSet").click(function () {
??????????????? var testData = JSON.stringify({ "name": "李小明" });
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetDataSet",
??????????????????? type: "post",
??????????????????? data: "{}",
??????????????????? dataType: "xml",
??????????????????? contentType: "application/xml;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //DataSet返回的是一個XML的對象,所以要使用each方法進行遍歷返回
??????????????????????? try
??????????????????????? {
??????????????????????????? $(data).find("MyTable").each(function () {
??????????????????????????????? $("#divContent").append("你得到的對象的ID是:" + $(this).find("Id").text()
??????????????????????????????????? + ",名字是:" + $(this).find("Name").text()
??????????????????????????????????? +",年齡是:"+$(this).find("Age").text()+",家庭地址是:"+$(this).find("Address").text()+"</br>");
??????????????????????????? });
??????????????????????? }catch(e)
??????????????????????? {
??????????????????????????? alert("出錯啦!"+e);
??????????????????????? }
??????????????????????
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的XML格式的數據
??????????? $("#btnGetXml").click(function () {
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetXml",
??????????????????? type: "post",
??????????????????? data: "{}",
??????????????????? dataType: "xml",
??????????????????? contentType: "application/xml;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //獲取的到是xml格式的字符串,解析
??????????????????????? $(data).find("Person").each(function () {
??????????????????????????? $("#divContent").append("您從后臺獲取到的Xml文檔中Person對象的ID是:" + $(this).find("id").text()
??????????????????????????????? +",名字是:"+$(this).find("name").text()+"</br>");
??????????????????????? })
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的Json格式的數據
??????????? $("#btnGetJsonData").click(function () {
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/GetJsonData",
??????????????????? type: "post",
??????????????????? data: "{}",
??????????????????? dataType: "json",
??????????????????? contentType: "application/json;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //將json字符串轉換成json對象
??????????????????????? var jsonObj = eval("(" + data.d + ")");//后臺給的一個json數組
??????????????????????? $(jsonObj).each(function (index, value) {
??????????????????????????? $("#divContent").append("從后臺獲取到的json對象的名字是:" + jsonObj[index].Name
??????????????????????????????? + ",年齡是:" + jsonObj[index].Age);
??????????????????????? });
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //獲取后臺方法返回的讀取的XML文件的數據
??????????? $("#btnGetXmlFile").click(function () {
??????????????? $.ajax({
??????????????????? url: "../ws/MyWebService.asmx/ReadXml",
??????????????????? type: "post",
??????????????????? data: "{}",
??????????????????? dataType: "xml",
??????????????????? contentType: "application/xml;charset=utf-8",
??????????????????? success: function (data) {
??????????????????????? //獲取的到是xml格式的字符串,解析
??????????????????????? $(data).find("Config").each(function () {
??????????????????????????? //得到的是一個Person對象數組
??????????????????????????? var $person = $(this).find("Person");
??????????????????????????? $person.each(function (index, value) {
??????????????????????????????? //通過js的相關屬性來獲取屬性的值
??????????????????????????????? var domPerson = $person.get(index);//獲取Dom對象
??????????????????????????????? $("#divContent").append("您從后臺讀取到Config的Person配置的ID是:"
??????????????????????????????????? + domPerson.getAttribute("Id") + ",名字是:" + domPerson.getAttribute("Name")
??????????????????????????????????? + ",年齡是:" + domPerson.getAttribute("Age")+"</br>");
??????????????????????????? });
??????????????????????? })
??????????????????? },
??????????????????? error: function (xmlHttpRequest, textStatus, errorInfo) {
??????????????????????? alert(errorInfo);
??????????????????? }
??????????????? });
??????????? });

??????????? //Ajax方法為用戶提供反饋,加載遮罩層之類的
??????????? $("#loading").ajaxStart(function () {
??????????????? $(this).show();
??????????? }).ajaxStop(function () {
??????????????? $(this).hide();
??????????? });
??????????? //加載按鈕的移入移除事件
??????????? $("input[type=button]").hover(function () {
??????????????? $(this).addClass("hover");
??????????? }, function () {
??????????????? $(this).removeClass("hover");
??????????? })
??????? });
??? </script>
</head>
<body>
??? <input type="button" id="btnGetTextNoParam" value="獲取后臺方法返回的文本格式的字符串,無參數傳遞" /><br />
??? <input type="button" id="btnGetTextParam" value="獲取后臺方法返回的文本格式的字符串,有參數參數傳遞" /><br />
?? <input type="button" id="btnGetList" value="獲取后臺方法返回的集合格式的數據" /><br />
??? <input type="button" id="btnGetClass" value="獲取后臺方法返回復合類型的變量" /><br />
??? <input type="button" id="btnGetDataSet" value="獲取后臺方法返回的DataSet(XML)格式的數據" /><br />
??? <input type="button" id="btnGetXml" value="獲取后臺方法返回的XML格式的數據" /><br />
??? <input type="button" id="btnGetJsonData" value="獲取后臺方法返回的Json格式的數據" /><br />
??? <input type="button" id="btnGetXmlFile" value="獲取后臺方法返回的讀取的XML文件的數據" /><br />
???? <div id="loading" style="display:none;">
???????? 服務器處理中,請稍后。
???? </div>

??? <div id="divContent" style="background-color:yellow;border:1px solid #f00">

??? </div>

</body>
</html>

3、用到的讀取xml文件的文件是:

<?xml version="1.0" encoding="utf-8" ?>
<Config>
? <Person Id="9527" Name="張三" Age="19">我是一個測試的人1</Person>
? <Person Id="5345" Name="李四" Age="39">我是一個測試的人2</Person>
? <Person Id="1234" Name="王二麻子" Age="45">我是一個測試的人3</Person>
</Config>

?

以上是直接貼代碼,僅供初學者使用,哈哈,我也菜鳥一個,相互學些

轉載于:https://www.cnblogs.com/StevenDu/p/ajax.html

總結

以上是生活随笔為你收集整理的用JQuery中的Ajax方法获取web service等后台程序中的方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。