Code for communication between javascript and webservice

Source: Internet
Author: User

Here, I choose to convert xml directly to json for subsequent processing of javascript applications. I used the. net platform to build a simple webservice.
Request. asmx
Copy codeThe 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>
/// Summary of 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 )});
}
}

The above is just a simple test to facilitate subsequent use of javascript to process different types of data
For javascript, the xmlhttprequest object must be used to access the server. However, for simplicity, I did not consider compatibility issues and directly used the xmlhttprequest object (I used chrome as the test browser ), for this reason, I use the AjaxClient class for http operations (Post method). The WebService class is used to encapsulate and process webservice (the AjaxClient class is called as the operation class). The JsonConverter class is used to process xml data and convert it to json data.
Common. js (including the JsonConverter class)
Copy codeThe 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 <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>
AjaxClient. js
Copy codeThe Code is as follows:
// 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 & gt; = 20000)
Break;
}
Return msgList. length = 0? Null: msgList. shift ();
}
This. Close = function ()
{
If (! IsRunning)
{
IsOpen = false;
Xmlhttp = null;
}
}
}

WebService. js
Copy codeThe Code is as follows:
// 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;
}
}

The call is simple.
Copy codeThe Code is as follows:
Var webService = new WebService ('HTTP: // localhost/NightKidsWebService/Request. asmx ');
WebService. Request ("GetResourceList", null );
Alert (JsonConverter. ConvertFromXML (webService. GetResponse (). firstChild ));

The first parameter in the Request method corresponds to different service names, and the second parameter is added to the corresponding service parameter table (json format, for example: {id: 123, name: 'nightkids '})

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.