DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript與webservice的通信實現代碼
javascript與webservice的通信實現代碼
編輯:關於JavaScript     
在我這裡,我選擇將xml直接轉換為json,以便後續javascript應用的處理。我使用.net平台構建簡單的webservice。
Request.asmx
復制代碼 代碼如下:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.Drawing.Imaging;
namespace NightKidsServices
{
/// <summary>
/// Service1 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class TestService :WebService
{
private static int picNum = -1;
[WebMethod]
public Resource GetResource()
{
return Resource.CreateResource("pic2", "asdfasd", 0);
}
[WebMethod]
public string HelloWorld()
{
return "Hello";
}
[WebMethod]
public byte[] GetPic()
{
picNum = (picNum + 1) % 32;
Image image = Image.FromFile(this.Server.MapPath("jpeg/" + (picNum+1).ToString() + ".bmp"));
MemoryStream mem=new MemoryStream();
image.Save(mem, ImageFormat.Jpeg);
return mem.GetBuffer();
}
[WebMethod]
public List<Resource> GetResourceList()
{
return new List<Resource>(new Resource[] { Resource.CreateResource("pic1", "jpeg/1.bmp", 0),Resource.CreateResource("pic2", "jepg/2.bmp", 0), Resource.CreateResource("pic3", "jpeg/3.bmp", 0), Resource.CreateResource("pic4", "jepg/4.bmp", 0) });
}
}

以上只是一個簡單的測試使用,便於後續使用javascript處理不同類型的數據
對於javascript,肯定是使用xmlhttprequest對象來訪問服務器端的,不過這裡為了簡單,我沒有考慮兼容性問題,直接使用xmlhttprequest對象(我使用chrome浏覽器作為測試浏覽器),為此我使用AjaxClient類來進行http操作(Post 方法),WebService類來封裝處理webservice(調用AjaxClient類作為操作類),JsonConverter類處理xml數據轉換為json數據
common.js(包含JsonConverter類)
復制代碼 代碼如下:
// JavaScript Document
function $(id)
{
return document.getElementById(id);
}
function GetXmlHttp()
{
if(window.XMLHttpRequest)
return new XMLHttpRequest();
}
var JsonConverter={};
JsonConverter.FlagStack=[];
JsonConverter.ConvertFromXML=function(xmlRootNode)
{
if(!xmlRootNode)
return;
var converter={};
converter.render=function(node,isArrayElement)
{
var returnStr='';
var isArray=false;
if(node.childNodes.length==1)
{
returnStr+=node.nodeName+':' + "'" + node.firstChild.nodeValue + "'" ;
if(node==xmlRootNode)
returnStr='{' + returnStr + '}';
return returnStr;
}
isOneNode=false;
if(node.nodeName.match("ArrayOf*"))
isArray=true;
if(isArray)
returnStr+='[';
else
{
returnStr+='{';
if(!(isArrayElement || xmlRootNode==node))
returnStr=node.nodeName + ':' + returnStr;
}
for(var i=1;i<node.childNodes.length;i+=2)
{
returnStr+=this.render(node.childNodes[i],isArray) + ',';
}
returnStr=returnStr.slice(0,-1);
if(isArray)
returnStr+=']';
else
returnStr+='}';
return returnStr;
}
//alert(converter.render(xmlRootNode));
return eval('(' + converter.render(xmlRootNode) + ')');
}

<SPAN style="FONT-FAMILY: verdana, 'courier new'"><SPAN style="FONT-SIZE: 14px; LINE-HEIGHT: 21px; WHITE-SPACE: normal"><BR></SPAN></SPAN>
AjaxClient.js
復制代碼 代碼如下:
// JavaScript Document
function AjaxClient(url)
{
var xmlhttp=GetXmlHttp();
var request_url=url;
var msgList=new Array();
var isOpen=false;
var isRunning=false;
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==xmlhttp.DONE)
{
isRunning=false;
if (xmlhttp.status==200)
{
msgList.push(xmlhttp.responseXML);
}
}
}
this.Open=function()
{
if(xmlhttp==null)
xmlhttp=GetXmlHttp();
isOpen=true;
if(xmlhttp==null)
isOpen=false;
}
this.Send=function(msg)
{
if (isOpen)
{
xmlhttp.open("POST",request_url,false);
//alert(request_url);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length",msg==null?0:msg.length);
//xmlhttp.setRequestHeader("Keep-Alive","ON");
xmlhttp.send(msg==null?"":msg);
isRunning=true;
}
}
this.GetUrl=function()
{
return request_url.length==0?'':request_url;
}
this.SetUrl=function(url)
{
request_url=url;
}
this.Receive=function()
{
var num=0;
while(!msgList.length)
{
num++;
if (num>=20000)
break;
}
return msgList.length==0?null:msgList.shift();
}
this.Close=function()
{
if(!isRunning)
{
isOpen=false;
xmlhttp=null;
}
}
}

WebService.js
復制代碼 代碼如下:
// JavaScript Document
function WebService(url)
{
var ajaxclient=new AjaxClient(null);
var requestUrl=url;
var responseMsg=null;
this.Request=function(requestName,paraList)
{
var url=requestUrl +'/' + requestName;
var sendData='';
ajaxclient.SetUrl(url);
ajaxclient.Open();
//alert(ajaxclient.GetUrl());
if (paraList!=null)
{
for(var obj in paraList)
sendData+=obj.toString() + '=' + paraList[obj] + '&';
sendData=sendData.slice(0,-1);
}
ajaxclient.Send(sendData);
//ajaxclient.Close();
//responseMsg=XMLtoJSON(ajaxclient.Receive());
//for(var obj in responseMsg)
// alert(obj.toString() + ':' + responseMsg[obj].toString());
responseMsg=ajaxclient.Receive();
}
this.GetResponse=function()
{
return responseMsg;
}
}

調用很簡單,只需
復制代碼 代碼如下:
var webService=new WebService('http://localhost/NightKidsWebService/Request.asmx');
webService.Request("GetResourceList",null);
alert(JsonConverter.ConvertFromXML(webService.GetResponse().firstChild));

在Request方法裡面的第一個參數對應不同的服務名稱,第二個參數加入對應的服務的參數表(json格式,例如:{id:123,name:'nightKids'})
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved