一個程式碼把它寫到blog上
前台
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html> <head runat="server"> <title>ajax+WebServer及Dataset轉xml操作執行個體</title> <script type="text/javascript" language="javascript"> var xmlhttp;//聲明一個變數 try { xmlhttp=new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) { try { xmlhttp= new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { try { xmlhttp=new XMLHttpRequest(); } catch(e) { } } } var temp=new Array(); var url="WebService.asmx/HelloWorld"; xmlhttp.open("post",url,true); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) { if(xmlhttp.status==200) { var xmldoc=xmlhttp.responseText; xmldocxmldoc=xmldoc.replace(/</gi,"<"); xmldocxmldoc=xmldoc.replace(/>/gi,">"); var xmlDoc2 = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc2.async="false"; xmlDoc2.loadXML(xmldoc); if(xmlDoc2.parseError.errorCode != 0) { alert("讀取xml出錯"); } else { if(xmlDoc2.readyState==4) { var id = xmlDoc2.documentElement.selectNodes("//id"); var name = xmlDoc2.documentElement.selectNodes("//name"); var temp=""; for(var i=0;i<id.length;i++) { temp+=id(i).text+" "+name(i).text+"<br>"; } document.getElementById("list").innerHTML=temp; } else { alert("載入失敗"); } } } else { alert(xmlhttp.status); } } } xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(null); </script> </head> <body> <form id="form1" runat="server"> <div> <span id="list"></span> </div> </form> </body> </html>
WebService.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" class="WebService" %>
WebService.cs
using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Data.SqlClient; using System.Xml;
/// <summary> /// WebService 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService {
public WebService () {
//如果使用設計的組件,請取消注釋以下行 //InitializeComponent(); }
[WebMethod] public string HelloWorld() { string conn = "server=127.0.0.1;database=temp;min pool size=40;User ID=sa;Password=sa123"; SqlConnection myConn = new SqlConnection(conn); myConn.Open(); string cmd = "select * from [user] order by id desc"; SqlDataAdapter myRead = new SqlDataAdapter(cmd, myConn); DataSet mySet = new DataSet(); myRead.Fill(mySet, "user"); myConn.Close(); return mySet.GetXml(); } }
資料庫名稱temp
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[user] GO
CREATE TABLE [dbo].[user] ( [id] [int] IDENTITY (1, 1) NOT NULL , [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ) ON [PRIMARY] GO
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/sendling/archive/2008/10/20/3107647.aspx