Home > Web Front-end > JS Tutorial > Communication implementation code between javascript and webservice_javascript skills

Communication implementation code between javascript and webservice_javascript skills

WBOY
Release: 2016-05-16 18:13:26
Original
1021 people have browsed it

In my case, I chose to convert xml directly to json for subsequent processing by javascript application. I'm building a simple webservice using .net platform.
Request.asmx

Copy code The code is as follows:

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 description of 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) });
}
}

The above is just a simple test use, It is convenient for subsequent use of JavaScript to process different types of data
For JavaScript, the xmlhttprequest object must be used to access the server side. However, for the sake of simplicity, I did not consider compatibility issues and directly used the xmlhttprequest object (I used the Chrome browser as a test browser device), for this I use the AjaxClient class to perform http operations (Post method), the WebService class to encapsulate and process webservice (call the AjaxClient class as the operation class), and the JsonConverter class to process xml data and convert it to json data
common.js (contains JsonConverter class)
Copy code The code is as follows:

// 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
Copy the code The code is as follows:

// JavaScript 문서
function AjaxClient(url)
{
var xmlhttp=GetXmlHttp();
var request_url=url;
var msgList=new 배열();
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 문서
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));

다른 이름으로 요청하는 방법은 다음과 같습니다. 이름:'nightKids '})
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template