Web Service and Ajax to implement an addition operation;
1. Create an ASP. Net web project;
2. Add a web service to the project;
Namespace Ajaxwcf { /// <Summary> /// Ajaxservice Summary /// </Summary> [ WebService (Namespace = "Http://tempuri.org /" )] [ Webservicebinding (Conformsto = Wsiprofiles . Basicprofile1_1)] [system. componentmodel. Toolboxitem ( False )]// To allow ASP. Net ajax to call this web service from a script, cancel the comments to the downstream. [System. Web. Script. Services. Scriptservice ] Public class Ajaxservice : System. Web. Services. WebService {[ Webmethod ] Public String Helloworld (){ Return "Hello World" ;}[ Webmethod ] Public int Add (Int A, Int B ){ Return A + B ;}}}
Note: you must add [system. Web. Script. Services.Scriptservice], And add the [webmethod]
Run the service and the result is as follows:
Adding js to the URL will provide the JS proxy File Download:
Add scriptmanager to the page and reference WebService
Asp : scriptmanager id =" scriptmanager1 " runat =" server "> scripts > Asp : scriptreference path = "~ /Ajaxservice. asmx/JS "/> scripts > Asp : scriptmanager >
Note: It can also be referenced here. The JS file you just downloaded can also be directly called by Web Service
Add two text boxes to input data.CodeAs follows:
< Form ID = "Form1" Runat = "Server"> < Div > < ASP : Scriptmanager ID = "Scriptmanager1" Runat = "Server"> < Scripts > < ASP : Scriptreference Path = "~ /Ajaxservice. asmx/JS "/> </ Scripts > </ ASP : Scriptmanager > A: < Input ID = "Txta" Type = "Text"/> < BR /> B: < Input ID = "Txtb" Type = "Text"/> < BR /> < Input ID = "Button1" Type = "Button" Value = "OK" Onclick = "Add ()"/> </ Div > </ Form >
Add js code in the head section;
<ScriptLanguage= "JavaScript"Type= "Text/JavaScript"> FunctionAdd (){VaRA = $ get ("Txta"). Value;VaRB = $ get ("Txtb"). Value; ajaxwcf. ajaxservice. Add (a, B, message );}FunctionMessage (RES) {alert (RES );}</Script>
Note: The ajaxwcf. ajaxservice. Add () method is a proxy method in the JS file, which can be found in the JS file;
The above figure shows all the code of the JS file. If you are interested, you can study it;
The final running result is as follows: