JAvascriptとwebserviceの通信実装コード

7237 ワード

ここでは、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
{
///
/// Service1
///

[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 GetResourceList()
{
return new List(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{
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) + ')');
}

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メソッドの最初のパラメータは異なるサービス名に対応し、2番目のパラメータは対応するサービスのパラメータテーブルを追加します(json形式、例えば:{id:123,name:'nightKids'})