I have read some articles on js webservice calling on the blog and Csdn, and it feels good. However, some of the programs they provide have more or less errors. I debugged them and posted them, you can share with us and record your learning.
I. Theory (omitted)
2. Example (minute 1, 2, 3)
1. webservice Compilation
View webservice code
1 using System.Web;
2 using System.Web.Services;
3 using System.Web.Services.Protocols;
4 using System.Xml.Linq;
5
6 [WebService(Namespace = "http://tempuri.org/")]
7 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
8 [System.Web.Script.Services.ScriptService]
9 public class WebService : System.Web.Services.WebService {
10 public WebService () {
11 }
12 [WebMethod]
13 public string SayHellow(string Name)
14 {
15 return "Hellow:" + Name;
16 }
17 }
2. js call webservice method 1
Call method 1
1 function RequestWebserviceByFunctionOne(value)
2 {
3
4 var URL = "http://localhost:2869/JsInvokeWebservice/WebService.asmx";
5 var data;
6 data = '<?xml version="1.0" encoding="utf-8"?>';
7 data = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">';
8 data = data + '<soap:Body>';
9 data = data + '<SayHellow xmlns="http://tempuri.org/" >';
10 data = data + '<Name>'+value+'</Name>';
11 data = data + '</SayHellow>';
12 data = data + '</soap:Body>';
13 data = data + '</soap:Envelope>';
14 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
15 xmlhttp.Open("POST", URL, false);
16 xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
17 xmlhttp.Send(data);
18 document.getElementById("data").innerHTML = xmlhttp.responseText;
19 }
3. js call webservice method 2
Method 2
1 function RequestWebserviceByFunctionTwo(data){
2
3 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
4 var URL="http://localhost:2869/JsInvokeWebservice/WebService.asmx/SayHellow?Name=Zach";
5 xmlhttp.Open("GET",URL, false);
6 xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
7 xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHellow");
8 xmlhttp.Send(data);
9 if(xmlhttp.status==200) {
10 document.write(xmlhttp.responseText);
11 }
12 xmlhttp = null;
13 }
Note: 1. For method 1, you can find the heap that needs to be sent on the webservice test page and add the corresponding parameters.
2. For method 2, the error "URL ended unexpectedly with"/SayHellow "and the request format cannot be identified" may be thrown,
Add the following code to the system. web Section in web. config to resolve the problem (<webServices> <protocols>
<Add name = "HttpPost"/> <add name = "HttpGet"/> </protocols> </webServices>)
3. Other asynchronous call codes have been described in this blog.