Because using JavaScript to invoke the Web service configuration is a bit cumbersome, so record it.
1. Create a new Web service (webservice.asmx)
2. Uncomment
[System.Web.Script.Services.ScriptService]
3. Before the public string HelloWorld () method, add
[Scriptmethod (Responseformat = Responseformat.json)]
and need
Using System.Web.Script.Services;
4. In Web. config, add
<system.web>
<webServices>
<protocols>
<add name= "HttpSoap"/>
<add name= "HttpPost"/>
<add name= "HttpGet"/>
<add name= "Documentation"/>
</protocols>
</webServices>
</system.web>
Full code:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Services;usingSystem.IO;usingSystem.Web.Script.Services;namespacewebservice{/// <summary> ///Summary description of WebService/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)] //to allow the Web service to be called from the script using ASP. NET AJAX, uncomment the downstream. [System.Web.Script.Services.ScriptService] Public classWebService:System.Web.Services.WebService {[WebMethod] [Scriptmethod (Responseformat=Responseformat.json)] Public stringHelloWorld () {Try { return "Hello World"; } Catch(Exception e) {file.writealltext (E.message+"\ r \ n"+ E.stacktrace,"Log.txt"); Throw; } } }}
Client calling Code:
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Headrunat= "Server"> <Metaname= "Generator"content= "HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" /> <title>Ajax</title> <Scriptsrc= "Jquery-2.0.3.min.js"type= "Text/javascript"></Script> <Script>functionAjax () {$.ajax ({type:"Post", ContentType:"Application/json", URL:"Http://localhost/webservice.asmx/HelloWorld", Success:function(msg) {alert (json.stringify (msg)); } });} </Script></Head><Body> <form> <inputID= "BTN"type= "button"onclick= "Ajax ()"value= "click" /> </form></Body></HTML>
Easy tutorial for calling ASP. NET WebService using jquery