I have always thought that WebService is only used to provide functional modules for external special business services, so I have always used the ashx File Processing backend. Today I read other people's articles and suddenly understand, webService can also process Ajax requests, and a file can process multiple requests at the same time, which is much more convenient than ashx and does not need to be created.
The following are two simple examples.
HTML section
View code
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
<SCRIPT type = "text/JavaScript" src = "JS/jquery-1.6.1.min.js"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
// The first test example
Function helloworld ()
{
$. Ajax ({
Type: "Post ",
URL: "WebService. asmx/helloworld ",
Data: "name = John ",
Success: function (MSG ){
Alert ("data saved:" + MSG );
}
});
}
// Add two numbers
Function add ()
{
$. Ajax ({
Type: "Post ",
URL: "WebService. asmx/Add ",
Data: "A =" + $ ("# text1"). Val () + "& B =" + $ ("# text2"). Val (),
Success: function (MSG ){
$ ("# Text3"). Val (MSG );
}
});
}
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Input id = "hello" type = "button" value = "button" onclick = "helloworld ()"/>
<Br/>
<Br/>
NUMA: <input id = "text1" style = "width: 31px" type = "text"/>
+ Numb: <input id = "text2" style = "width: 33px" type = "text" onblur = "add ()"/>
= <Input id = "text3" style = "width: 33px" type = "text"/> </div>
</Form>
</Body>
</Html>
WebService Section
View code
Using system;
Using system. Web;
Using system. collections;
Using system. Web. Services;
Using system. Web. Services. Protocols;
/// <Summary>
/// Summary of WebService
/// </Summary>
[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
Public class WebService: system. Web. Services. WebService {
Public WebService (){
// If you use the designed component, uncomment the following line
// Initializecomponent ();
}
[Webmethod]
Public void helloworld (){
If (context. request ["name"]! = NULL)
{
Context. response. Write (context. request ["name"]. tostring ());
}
Else
{
Context. response. Write ("no ");
}
}
[Webmethod]
Public String Hello (string name)
{
Return string. Format ("Hello {0}", name );
}
[Webmethod]
Public void add ()
{
If (context. request ["A"]! = NULL & context. request ["A"]! = NULL)
{
Int anum = int. parse (context. request ["A"]. tostring ());
Int bnum = int. parse (context. request ["B"]. tostring ());
Int result = anum + bnum;
Context. response. Write (result. tostring ());
}
Else
{
Context. response. Write ("no ");
}
}
}
Do not forget to reference the jquery. JS File