Web 服务:使用 Ajax 调用 Web 服务(XML SOAP 请求)






1.91/5 (4投票s)
2007年8月9日
1分钟阅读

23033

213
这是一个关于 Web Service 和 Ajax 的简单示例。 使用 SOAP 的 xmlRequest 调用 Web Service 方法。 这里的 Javascript 代码的编写方式类似于面向对象编程 (OOPS)。
引言
这是一个使用 AJAX 调用任何 Web Service 方法的简单示例。 这里的 Javascript 类似于 OOPs 的编写方式,因此您可以看到 Javascript 如何用作类和对象。 在这个项目中,我正在访问 C# 编程中常用的数据对象的值。
背景
此示例项目允许您添加、编辑、删除和查看员工信息,而无需任何回传。 使用 AJAX,它调用 webservice 方法,并从客户端到服务器以及相反方向操作数据。
使用代码
此示例项目包含三个不同的项目文件
1. CoreService
2. AjaxWeb
3. TestWebService
1. CoreSevice
它包含 EmployeeDO.cs 和 EmployeeDL.cs。 我没有为数据访问层和数据对象创建单独的项目,而是将其放在一个项目中。 这里我没有任何业务层,因为它只是一个示例。
2. AjaxWeb
这是实际的项目,我在其中使用 employee.aspx 来操作员工数据。 这里我有一个名为 "Employee.js" 的 javascript 文件。
//
// JScript File
var SEL_EMPID = "ddlEmployee";
var TXT_EMP_F_NAME = "txtFirstName";
var TXT_EMP_L_NAME = "txtLastName";
var TXT_COUNTRY = "txtCountry";
var IdPreFix = "ctl00_cphBody_";
var BTN_ADDNEW = "btnAddNew";
var BTN_SAVE = "btnSave";
var BTN_UPDATE = "btnUpdate";
var BTN_DELETE = "btnDelete";
function EmployeeDO()
{
"ltr" style="MARGIN-RIGHT: 0px">
//this.objEmpFirstName = function(){return document.getElementById(IdPreFix+SEL_EMPID);}
this.EmpID = document.getElementById(IdPreFix+SEL_EMPID);
this.EmpFirstName = document.getElementById(IdPreFix+TXT_EMP_F_NAME);
this.EmpLastName = document.getElementById(IdPreFix+TXT_EMP_L_NAME);
this.Country = document.getElementById(IdPreFix+TXT_COUNTRY);
}
function Buttons()
{
"ltr" style="MARGIN-RIGHT: 0px">
this.CtrlAddNew = document.getElementById(IdPreFix+BTN_ADDNEW);
this.CtrlSave = document.getElementById(IdPreFix+BTN_SAVE);
this.CtrlUpdate = document.getElementById(IdPreFix+BTN_UPDATE);
this.CtrlDelete = document.getElementById(IdPreFix+BTN_DELETE);
}
function ShowHide(Add,Update,Delete,Save,bCheck)
{
"ltr" style="MARGIN-RIGHT: 0px">
var objButtons = new Buttons();
var objEmployeeDO = new EmployeeDO();
if(objEmployeeDO.EmpID.selectedIndex == 0 && bCheck == true)
{
objButtons.CtrlAddNew.style.display = "block";
objButtons.CtrlUpdate.style.display = "none";
objButtons.CtrlDelete.style.display = "none";
objButtons.CtrlSave.style.display = "none";
}
else
{
objButtons.CtrlAddNew.style.display = Add;
objButtons.CtrlUpdate.style.display = Update;
objButtons.CtrlDelete.style.display = Delete;
objButtons.CtrlSave.style.display = Save;
}
}
function GetEmployee(obj)
{
"ltr" style="MARGIN-RIGHT: 0px">
var EmpId = obj.value;
var employeeProxy = new EmployeeProxy();
employeeProxy.onDeserialized = PopulateEmployee;
employeeProxy.onXmlDataLoaded = onShowResponseXml;
if(EmpId == "0")
{
var objEmployeeDO = new EmployeeDO();
objEmployeeDO.EmpID.selectedIndex = 0;
objEmployeeDO.EmpFirstName.value = "";
objEmployeeDO.EmpLastName.value = "";
objEmployeeDO.Country.value = "";
ShowHide('block','none','none','none',false);
}
else
{
employeeProxy.getEmployee(EmpId);
ShowHide('block','block','block','none',false);
}
}
function AddNewEmployee()
{
"ltr" style="MARGIN-RIGHT: 0px">
var objEmployeeDO = new EmployeeDO();
objEmployeeDO.EmpID.selectedIndex = 0;
objEmployeeDO.EmpFirstName.value = "";
objEmployeeDO.EmpLastName.value = "";
objEmployeeDO.Country.value = "";
ShowHide('none','none','none','block',false);
}
function SaveEmployee()
{
"ltr" style="MARGIN-RIGHT: 0px">
var employeeProxy = new EmployeeProxy();
employeeProxy.onDeserialized = AfterAddEmployee;
employeeProxy.onXmlDataLoaded = onShowResponseXml;
var objEmployeeDO = new EmployeeDO();
if(objEmployeeDO.EmpFirstName.value == "" || objEmployeeDO.EmpLastName.value == "")
alert("Fill Required Fields");
else
{
ShowHide('block','block','block','none',false);
employeeProxy.insertEmployee(objEmployeeDO.EmpFirstName.value,objEmployeeDO.EmpLastName.value,objEmployeeDO.Country.value);
}
}
function UpdateEmployee()
{
"ltr" style="MARGIN-RIGHT: 0px">
//ShowHide('block','block','block','none');
var employeeProxy = new EmployeeProxy();
employeeProxy.onDeserialized = AfterUpdateEmployee;
employeeProxy.onXmlDataLoaded = onShowResponseXml;
var objEmployeeDO = new EmployeeDO();
if(objEmployeeDO.EmpFirstName.value == "" || objEmployeeDO.EmpLastName.value == "")
alert("Fill Required Fields");
else
{
ShowHide('block','none','block','none',false);
employeeProxy.updateEmployee(objEmployeeDO.EmpID.value,objEmployeeDO.EmpFirstName.value,objEmployeeDO.EmpLastName.value,objEmployeeDO.Country.value);
}
}
function DeleteEmployee()
{
"ltr" style="MARGIN-RIGHT: 0px">
ShowHide('block','block','block','none',false);
var employeeProxy = new EmployeeProxy();
employeeProxy.onDeserialized = AfterDeleteEmployee;
employeeProxy.onXmlDataLoaded = onShowResponseXml;
var objEmployeeDO = new EmployeeDO();
if(objEmployeeDO.EmpID.value == "0")
{
ShowHide('block','block','none','none',false);
}
else
{
employeeProxy.deleteEmployee(objEmployeeDO.EmpID.value);
}
}
function PopulateEmployee(result)
{
"ltr" style="MARGIN-RIGHT: 0px">
if(result.length > 0)
{
var objEmployeeDO = new EmployeeDO();
var index = 0;
objEmployeeDO.EmpID.value = result[index].EmpID;
objEmployeeDO.EmpFirstName.value = result[index].EmpFirstName;
objEmployeeDO.EmpLastName.value = result[index].EmpLastName;
objEmployeeDO.Country.value = result[index].Country;
}
/* var tableHtm = '';
var trHtm = '';
for(var index = 0; index < result.length; index++)
{
var row = new Array();
trHtm = '<tr>';
row.push(result[index].EmpID);
row.push(result[index].EmpFirstName);
row.push(result[index].EmpLastName);
row.push(result[index].Country);
trHtm += '<td>' + row[0] + '</td>';
trHtm += '<td>' + row[1] + '</td>';
trHtm += '<td>' + row[2] + '</td>';
trHtm += '<td>' + row[3] + '</td>';
trHtm += '</tr>';
}
if(result.length)
{
tableHtm = '<table>' + trHtm + '</table>';
//grdData.innerHTML = tableHtm;
}
alert(tableHtm);*/
}
function AfterAddEmployee(result)
{
"ltr">
var objEmployeeDO = new EmployeeDO();
var i = objEmployeeDO.EmpID.options.length;
objEmployeeDO.EmpID.options[i] = new Option(objEmployeeDO.EmpFirstName.value,result);
objEmployeeDO.EmpID.selectedIndex = i;
}
function AfterDeleteEmployee(result)
{
"ltr">
if(eval(result) != 0)
{
alert("Deleted Successfully");
}
var objEmployeeDO = new EmployeeDO();
var i = objEmployeeDO.EmpID.selectedIndex;
objEmployeeDO.EmpID.options[i] = null;
objEmployeeDO.EmpID.selectedIndex = 0;
objEmployeeDO.EmpFirstName.value = "";
objEmployeeDO.EmpLastName.value = "";
objEmployeeDO.Country.value = "";
ShowHide('block','none','none','none',false);
}
function AfterUpdateEmployee(result)
{
"ltr">
if(eval(result) != 0)
{
alert("Updated Successfully");
}
}
function onShowResponseXml(responseXml)
{
"ltr">
//alert(responseXml);
}
function getIdPrefix(obj)
{
"ltr">
var IdIndex = obj.id.lastIndexOf('_');
IdPreFix = obj.id.substring(0,IdIndex+1);
}
//
如果您查看上面的代码,它很容易使用。
3. TestWebService
这是我的 Web Service 项目。 这里我有像 GetEmployee(), AddEmployee() 等 Web 方法。
Employee.asmx.cs 的代码如下
//
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Collections.Generic;
using CoreService;
namespace TestWebService
{
/// <summary>
/// Summary description for employee
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class employee : System.Web.Services.WebService
{
[WebMethod]
public List<EmployeeDO> GetEmployee(int EmpID)
{
try
{
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.GetEmployee(EmpID);
}
catch
{
throw;
}
}
[WebMethod]
public List<EmployeeDO> GetEmployees()
{
try
{
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.GetEmployees();
}
catch
{
throw;
}
}
[WebMethod]
public int InsertEmployee(string EmpFirstName, string EmpLastName, string Country)
{
try
{
EmployeeDO objEmpDO = new EmployeeDO(EmpFirstName,EmpLastName,Country);
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.InsertEmployee(objEmpDO);
}
catch
{
throw;
}
}
[WebMethod]
public int UpdateEmployee(int EmpID,string EmpFirstName, string EmpLastName, string Country)
{
try
{
EmployeeDO objEmpDO = new EmployeeDO(EmpID,EmpFirstName,EmpLastName,Country);
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.UpdateEmployee(objEmpDO);
}
catch
{
throw;
}
}
[WebMethod]
public string GetEmployeeXML(int EmpID,string EmpFirstName, string EmpLastName, string Country)
{
try
{
EmployeeDO objEmpDO = new EmployeeDO(EmpID,EmpFirstName,EmpLastName,Country);
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.GetEmployeeXML(objEmpDO);
}
catch
{
throw;
}
}
[WebMethod]
public int DeleteEmployee(int EmpID)
{
try
{
EmployeeDL objEmpDL = new EmployeeDL();
return objEmpDL.DeleteEmployee(EmpID);
}
catch
{
throw;
}
}
}
}
//
WebService.js 的代码如下
// JScript File
//proxy constants
var emptyResponse = -1;
function deserializeXML(responseXml)
{
var result = responseXml.documentElement.selectSingleNode("./child::*/child::*/child::*");
if(result.firstChild==null)
return emptyResponse;
if(result.firstChild.nodeType==1)
{
var resultArray = new Array();
for(var index = 0; index < result.childNodes.length; index++)
{
//convert the xml node into js object and add item to result array
resultItem = result.childNodes[index];
var objDO = new Object();
for(var index1 = 0; index1 < resultItem.childNodes.length; index1++)
{
objDO[resultItem.childNodes[index1].nodeName] = resultItem.childNodes[index1].text;
}
resultArray.push(objDO);
}
return resultArray;
}
else
//return the result value without any serialization
//as return value is supposed to be a primitive data type such as int, boolean .etc
return result.firstChild.nodeValue;
}
function ProxyHelper()
{
var httpObj = new ActiveXObject("Microsoft.XMLHTTP");
httpObj.onreadystatechange = onReadyStateChange;
var thisRef = this;
this.onDataLoaded;
this.send = function(strRequest , soapAction, servicePath)
{
httpObj.open("POST", servicePath, true);
httpObj.setRequestHeader("SOAPAction",soapAction );
httpObj.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
httpObj.send(strRequest);
}
function onReadyStateChange()
{
if(httpObj.readyState == 4)
{
if(httpObj.status == 200)
{
if(thisRef.onDataLoaded!=null)
{
httpObj.responseXml.setProperty("SelectionLanguage", "XPath");
thisRef.onDataLoaded(httpObj.responseXml);
}
}
else
{
alert("Status: "+httpObj.statusText+".\nResponseText: "+httpObj.responseText);
}
}
}
}
function EmployeeProxy()
{
//var path = "../TestWebService/Employee.asmx";
var path = "https:///TestWebService/Employee.asmx";
var proxyHelper = new ProxyHelper();
proxyHelper.onDataLoaded = onDeserialize;
var thisRef = this;
this.onDeserialized;
this.onXmlDataLoaded;
function onDeserialize(responseXml)
{
if(thisRef.onXmlDataLoaded!=null)
thisRef.onXmlDataLoaded(responseXml);
if(thisRef.onDeserialized==null)
return;
thisRef.onDeserialized(deserializeXML(responseXml));
}
this.getEmployee = function(EmpID)
{
var soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soapRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
soapRequest += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> ";
soapRequest += " <soap:Body><GetEmployee xmlns=\"http://tempuri.org/\"><EmpID>" + EmpID + "</EmpID></GetEmployee></soap:Body></soap:Envelope>";
proxyHelper.send(soapRequest,"http://tempuri.org/GetEmployee",path);
}
this.getEmployees = function()
{
var soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soapRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
soapRequest += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> ";
soapRequest += " <soap:Body><GetEmployees xmlns=\"http://tempuri.org/\" /></soap:Body></soap:Envelope>";
proxyHelper.send(soapRequest,"http://tempuri.org/GetEmployees",path);
}
this.deleteEmployee = function(EmpID)
{
var soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soapRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
soapRequest += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> ";
soapRequest += " <soap:Body><DeleteEmployee xmlns=\"http://tempuri.org/\"><EmpID>" + EmpID + "</EmpID></DeleteEmployee></soap:Body></soap:Envelope>";
proxyHelper.send(soapRequest,"http://tempuri.org/DeleteEmployee",path);
}
this.insertEmployee = function(EmpFirstName,EmpLastName,Country)
{
var soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soapRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
soapRequest += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> ";
soapRequest += " <soap:Body><InsertEmployee xmlns=\"http://tempuri.org/\">";
soapRequest += "<EmpFirstName>" + EmpFirstName + "</EmpFirstName>";
soapRequest += "<EmpLastName>" + EmpLastName + "</EmpLastName>";
soapRequest += "<Country>" + Country + "</Country>";
soapRequest += "</InsertEmployee></soap:Body></soap:Envelope>";
proxyHelper.send(soapRequest,"http://tempuri.org/InsertEmployee",path);
}
this.updateEmployee = function(EmpID,EmpFirstName,EmpLastName,Country)
{
var soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soapRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
soapRequest += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> ";
soapRequest += " <soap:Body><UpdateEmployee xmlns=\"http://tempuri.org/\">";
soapRequest += "<EmpID>" + EmpID + "</EmpID>";
soapRequest += "<EmpFirstName>" + EmpFirstName + "</EmpFirstName>";
soapRequest += "<EmpLastName>" + EmpLastName + "</EmpLastName>";
soapRequest += "<Country>" + Country + "</Country>";
soapRequest += "</UpdateEmployee></soap:Body></soap:Envelope>";
proxyHelper.send(soapRequest,"http://tempuri.org/UpdateEmployee",path);
}
}
//
关注点
在这里我学到了很多如何以类似于 OOPs 的方式编写 javascript 的知识。
参考
我从 Andrew Golik 的 关于 Ajax DataGrid 的文章中获得了创建此示例的想法。