Share XmlHttpRequest's experience in calling Webservice

Source: Internet
Author: User

First, because JSON is convenient for JS, JSON is used to request and return data. Instantiate an xmlHttpRequest object in JS, and then follow the instructions on the Internet to POST the address: asmx page address/Web method name. In RequestHeader, set Content-Type to application/json; charset = UTF-8; and SOAPAction to Web method name. The parameters of the Web method are sent out in JSON format.
The Code is as follows: Copy codeThe Code is as follows: function getXmlHttp (){
Var xmlHttp;
If (window. XMLHttpRequest)
{// Code for IE7 +, Firefox, Chrome, Opera, Safari
XmlHttp = new XMLHttpRequest ();
}
Else
{// Code for IE6, IE5
XmlHttp = new ActiveXObject ('Microsoft. xmlhttp ');
}
Return xmlHttp;
}
Function webservice (url, action, data, success, error, complete, failed ){
Var xmlHttp = getXmlHttp (); // get the XMLHttpRequest object
XmlHttp. open ('post', url + '/' + action, true); // asynchronous request data
XmlHttp. onreadystatechange = function (){
If (xmlHttp. readyState = 4 ){
Try {
If (xmlHttp. status = 200 & typeof (success) = 'function '){
Success (xmlHttp. responseText );
}
Else if (xmlHttp. status/100 = 4 | xmlHttp. status/100 = 5) & typeof (error) = 'function '){
Error (xmlHttp. responseText, xmlHttp. status );
}
Else if (xmlHttp. status/100 = 200 & typeof (complete) = 'function '){
Complete (xmlHttp. responseText, xmlHttp. status );
}
Else if (typeof (failed) = 'function '){
Failed (xmlHttp. responseText, xmlHttp. status );
}
}
Catch (e ){
}
}
}
XmlHttp. setRequestHeader ('content-type', 'application/json; charset = UTF-8 ');
XmlHttp. setRequestHeader ('soapaction', action );
XmlHttp. send (data );
}

For example, the request calls the HelloWorld method in Webservice1:Copy codeThe Code is as follows: webservice ('/Webservice1.asmx', 'helloworld', '{}', function (msg) {alert (msg );});

Before calling the [System. web. script. services. scriptService] cancel the annotation. After the call, a warning window is displayed: {"d": "Hello World "}. When the Content-Type is set to text/xml, the Content of the warning window changes to <? Xml version = "1.0" encoding = "UTF-8"?> <String xmlns = "http://tempuri.org/"> Hello World </string>.
At this time, although the request with the parameter "{}" or JSON format is in XML format, because Hello World does not have a parameter, the content format is ignored and the normal return value can be returned.
If you modify the HelloWorld method of the server, add a string-type parameter somebody.Copy codeThe Code is as follows: [WebMethod]
Public string HelloWorld (string somebody ){
Return "Hello World & Hello," + somebody + "! ";
}

Change the Content-Type of the Request back to application/json, and change the transfer parameter to {"somebody": "Krime"}. After the call, the pop-up window Content becomes {d: "Hello World & Hello, krime! "}.
However, if you change Content-Type to text/xml directly, the server will report an error after calling: System. InvalidOperationException: Invalid request format: text/xml; charset = UTF-8. In System. Web. Services. Protocols. HttpServerProtocol. ReadParameters (), in System. Web. Services. Protocols. WebServiceHandler. CoreProcessRequest ()
So we modified the parameter format and changed the parameter format:Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Soap: Envelope xmlns: xsi = "The http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "The http://www.w3.org/2001/XMLSchema" xmlns: soap = "The http://schemas.xmlsoap.org/soap/envelope/">
<Soap: Body>
<HelloWorld xmlns = "http://tempuri.org/">
<Somebody> Krime </somebody>
</HelloWorld>
</Soap: Body>
</Soap: Envelope>

In this way, the XML results will be returned normally? Unexpectedly, the server still reports the same error.
After a long time, I almost got mad. Does ASP. NET suddenly not know XML? At this time, I went back to take a closer look at the Webservice debugging page examples and finally found a problem:Copy codeThe Code is as follows: POST/WebServiceTest/Webservice1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset = UTF-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"
<? Xml version = "1.0" encoding = "UTF-8"?>
<Soap: Envelope xmlns: xsi = "The http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "The http://www.w3.org/2001/XMLSchema" xmlns: soap = "The http://schemas.xmlsoap.org/soap/envelope/">
<Soap: Body>
<HelloWorld xmlns = "http://tempuri.org/">
<Somebody> string </somebody>
</HelloWorld>
</Soap: Body>
</Soap: Envelope>

The POST address is not followed by the/method name when the JSON data is requested, and the namespace must be added before the SOAPAction method name. Therefore, the request header of XMLHttpRequest is modified, and the url and action are modified accordingly. The XML result is returned normally: <? Xml version = "1.0" encoding = "UTF-8"?> <Soap: Envelope xmlns: soap = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema"> <soap: body> <HelloWorldResponse xmlns = "http://tempuri.org/"> <HelloWorldResult> Hello World & Hello, Krime! </HelloWorldResult> </HelloWorldResponse> </soap: Body> </soap: Envelope>
Later, I continued the test and found that when the request content type is application/json, SOAPAction can be ignored and not added, but the/method name must be added after the url; otherwise, the server will not return data. In text/xml requests, SOAPAction is required and a namespace must be added before it. no/method name is available after the url.
Finally, after summary, the code is changed to the final form:Copy codeThe Code is as follows: function getXmlHttp (){
Var xmlHttp;
If (window. XMLHttpRequest)
{// Code for IE7 +, Firefox, Chrome, Opera, Safari
XmlHttp = new XMLHttpRequest ();
}
Else
{// Code for IE6, IE5
XmlHttp = new ActiveXObject ('Microsoft. xmlhttp ');
}
Return xmlHttp;
}
Function webservice (url, options ){
If (typeof (url) = 'object') {// write the url in options
Options = url;
Url = url. url;
}
If (! Url) return;
If (options. dataType. toLowerCase () = 'json') {// when requesting data in json format, add "/method name" to the url"
Url = url + '/' + options. method;
}
Var xmlHttp = getXmlHttp (); // get the XMLHttpRequest object
XmlHttp. open ('post', url, true); // asynchronous request data
XmlHttp. onreadystatechange = function (){
If (xmlHttp. readyState = 4 ){
Try {
If (xmlHttp. status = 200 & typeof (options. success) = 'function '){
Options. success (xmlHttp. responseText );
}
Else if (xmlHttp. status/100 = 4 | xmlHttp. status/100 = 5) & typeof (options. error) = 'function '){
Options. error (xmlHttp. responseText, xmlHttp. status );
}
Else if (xmlHttp. status/100 = 200 & typeof (options. complete) = 'function '){
Options. complete (xmlHttp. responseText, xmlHttp. status );
}
Else if (typeof (options. failed) = 'function '){
Options. failed (xmlHttp. responseText, xmlHttp. status );
}
}
Catch (e ){
}
}
}
XmlHttp. setRequestHeader ('content-type', options. contentType); // you can specify the ContentType of the request header.
XmlHttp. setRequestHeader ('soapaction', options. namespace + options. method); // set SOAPAction
XmlHttp. send (options. data); // send parameter data
}

Request JSON data:Copy codeThe Code is as follows: window. onload = function (){
Var data = '{"somebody": "Krime "}';
Var options = {
Namespace: 'http: // tempuri.org /',
Method: 'helloworld ',
ContentType: 'application/json; charset = UTF-8 ',
DataType: 'json ',
Data: data,
Success: function (msg ){
Alert (msg );
}
};
Webservice ('HTTP: // localhost: 8003/WebServiceTest/Webservice1.asmx ', options );
};

Request XML data:Copy codeThe Code is as follows: window. onload = function (){
Var data = '<? Xml version = "1.0" encoding = "UTF-8"?> '
+ '<Soap: Envelope xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" xmlns: soap = "http://schemas.xmlsoap.org/soap/envelope/">'
+ '<Soap: Body>'
+ '<HelloWorld xmlns = "http://tempuri.org/">'
+ '<Somebody> Krime </somebody>'
+ '</HelloWorld>'
+ '</Soap: Body>'
+ '</Soap: Envelope> ';
Var options = {
Namespace: 'http: // tempuri.org /',
Method: 'helloworld ',
ContentType: 'text/xml; charset = UTF-8 ',
DataType: 'xml ',
Data: data,
Success: function (msg ){
Alert (msg );
}
};
Webservice ('HTTP: // localhost: 8003/WebServiceTest/Webservice1.asmx ', options );
};

The test is normal.
Note that when you request JSON data, if the returned type is DataTable, You need to convert it to the List of corresponding data entity classes and then return.

In the process of resolving the XML returned result, find another solution. The specific operation is to set ContentType to application/x-www-form-urlencoded, and the data body does not use JSON or xml soap packages, instead, use "arguement1 = XXX & arguement2 = XXX" similar to QueryString ". This method simulates the http post format of form data and sends each control value encoded as name = value pair.

In this case, you also need to add the/method name after the page address.

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.