http://oldboy-bj.taobao.com/

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

javascript与webservice的通信

关于javascript与webservice的通信,从理论上来说实现应该不难,主要是将服务器端的xml数据进行一个简单的处理然后以一种适当的形式展现成来。在我这里,我选择将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) });
        }
    }






view sourceprint?

1  





以上只是一个简单的测试使用,便于后续使用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,isArray) +
',';
        }
        returnStr
=returnStr.slice(0,-1);
        
if(isArray)
            returnStr
+='';
        
else
            returnStr
+='}';
        
return returnStr;
    }
   
//alert(converter.render(xmlRootNode));

return eval('('
+ converter.render(xmlRootNode) +
')');
}



view sourceprint?

1 <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;
    }
}






调用很简单,只需

view sourceprint?

1 var webService=new WebService('http://localhost/NightKidsWebService/Request.asmx');


2 webService.Request("GetResourceList",null);


3 alert(JsonConverter.ConvertFromXML(webService.GetResponse().firstChild));





在Request方法里面的第一个参数对应不同的服务名称,第二个参数加入对应的服务的参数表(json格式,例如:{id:123,name:'nightKids'})
本文转自www.35java.com

posted on 2011-01-01 19:55  老男孩咖啡  阅读(305)  评论(0)    收藏  举报