Share XMLHttpRequest Call WebService's little tips _javascript skills

Source: Internet
Author: User
Tags http post soap
First, because of the convenience of JSON for JS, consider requesting and returning data via JSON. Instantiate a XMLHttpRequest object in JS, and then post the address according to the instructions on the Web: ASMX page address/web method name. Setting Content-type as Application/json in Requestheader; Charset=utf-8,soapaction is set to the Web method name. The parameters of the Web method send out in JSON format.
The code is as follows:
Copy Code code 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 XMLHttpRequest Object
Xmlhttp.open (' POST ', url + '/' + action, true); Asynchronous request data
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4) {
try {
if (Xmlhttp.status = && 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 = && 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 Code code as follows:

WebService ('/webservice1.asmx ', ' HelloWorld ', ' {} ', function (msg) {alert (msg);});

Please remember to uncomment the [System.Web.Script.Services.ScriptService] above Webservice1 before calling, and you can see the pop-up warning window after the call: {"D": "Hello World"}. When the Content-type is set to Text/xml, the contents of the warning window become <?xml version= "1.0" encoding= "Utf-8"?> <string "xmlns=" http:// tempuri.org/">hello world</string>.
At this point, although the parameter "{}" is still in the form of JSON, the request is in XML format, but because Hello World has no parameters, it ignores the format of the content and can return the value normally.
If you modify the server-side HelloWorld method, add a string-type parameter somebody.
Copy Code code as follows:

[WebMethod]
public string HelloWorld (string somebody) {
Return "Hello World&hello," + Somebody + "!";
}

Change the request-side content-type back to Application/json, change the transfer parameter to {"Somebody": "Krime"}, and the pop-up window content after the call becomes {d: "Hello World&hello, krime!"}.
But if then directly to the content-type change to Text/xml, the server will be called after the error: System.InvalidOperationException: Request format is invalid: Text/xml; Charset=utf-8. At System.Web.Services.Protocols.HttpServerProtocol.ReadParameters () in System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest ()
So we change the parameter format, follow the WebService Debug page example, change the parameter to:
Copy Code code as follows:

<?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>
<somebody>Krime</somebody>
</HelloWorld>
</soap:Body>
</soap:Envelope>

So you should be able to return the results of the XML correctly? The results were unexpected and the server still reported the same error.
After a long time, almost crazy, do not asp.net suddenly do not know the XML? This time, go back and take a closer look at the example of WebService Debug page, and finally found a problem:
Copy Code code 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= "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>
<somebody>string</somebody>
</HelloWorld>
</soap:Body>
</soap:Envelope>

The address above post does not have the same/method name as when requesting JSON data, and the SOAPAction method name needs to be preceded by a namespace. Then modify the XMLHttpRequest request headers, URLs and action to do the corresponding changes, the results of the normal return of the results of the XML: <?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>Later continue to test, found that the request content type is Application/json, SOAPAction can be completely ignored, but the URL must be followed by the/method name, otherwise the server will not return data. When a request is Text/xml, the SOAPAction is required and preceded by a namespace, and the URL cannot be followed by A/method name.
Finally, after summing up, change the code to the final appearance:
Copy Code code 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 URL in Options
options = URL;
url = url.url;
}
if (!url) return;
if (options.dataType.toLowerCase () = = ' json ') {//Request JSON-formatted data, add "/method name" after URL
url = url + '/' + Options.method;
}
var xmlHttp = getxmlhttp (); Get XMLHttpRequest Object
Xmlhttp.open (' POST ', url, true); Asynchronous request data
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4) {
try {
if (Xmlhttp.status = && 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 = && 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); Set 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 Code code 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 Code code 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> '
+ ' + ' <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 in good condition.
It is important to note that when requesting JSON data, if the return type is a DataTable, the list<> that needs to be converted to the corresponding data entity class is returned.

In the process of solving the problem of returning XML, another workaround was found. In particular, the ContentType is set to application/x-www-form-urlencoded, and the data body does not use JSON or XML-formatted SOAP packets, but rather querystring "arguement1= Xxx&arguement2=xxx ". This method simulates the HTTP post format of the form data, and encodes each control value as a name = value pair to send out.

The page address in this case will also need to be appended with the/method name.

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.