javascript与webservice的通信实现代码


在我这里,我选择将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'})
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3