Home >Web Front-end >JS Tutorial >Share some experience of XmlHttpRequest calling Webservice_javascript skills

Share some experience of XmlHttpRequest calling Webservice_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:51:321169browse

First of all, because of the convenience of JSON for JS, consider requesting and returning data through JSON. Instantiate an xmlHttpRequest object in JS, and then follow the online instructions to POST the address: asmx page address/Web method name. Set Content-Type in RequestHeader to application/json; charset=utf-8, and set SOAPAction to the Web method name. The parameters of the Web method are sent out in JSON format.
The code is as follows:

Copy code The 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, request to call the HelloWorld method in Webservice1:
Copy code The code is as follows:

webservice('/Webservice1.asmx','HelloWorld','{ }',function (msg) { alert(msg); });

Please remember to uncomment [System.Web.Script.Services.ScriptService] on Webservice1 before calling. After calling, you can See a pop-up warning window: {"d": "Hello World"}. When Content-Type is set to text/xml, the content of the warning window becomes Hello World.
At this time, although the parameter "{}" is still in the form of JSON, the request is in XML format. However, because Hello World has no parameters, the format of the content is ignored and the value can be returned normally.
If you modify the HelloWorld method on the server side, add a string type parameter someone.
Copy code The code is as follows:

[WebMethod]
public string HelloWorld(string somebody ) {
return "Hello World&Hello, " somebody "!";
}

Change the Content-Type of the requester back to application/json, and change the transmission parameter to {"somebody": "Krime"}, after calling the pop-up window content becomes {d: "Hello World&Hello, Krime!"}.
But if you directly change the Content-Type to text/xml at this time, the server will report an error after the call: System.InvalidOperationException: The request format is invalid: text/xml; charset=UTF-8. In System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() In System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
So we also modify the parameter format. According to the example of the Webservice debugging page, change the parameters Copy the code for:
The code is as follows:





Krime




This should be able to return XML results normally, right? The result was unexpected, the server still reported the same error.
After struggling for a long time, I almost went crazy. Could it be that ASP.NET suddenly doesn’t understand XML? At this time, go back and take a closer look at the example of the Webservice debugging page, and finally found a problem:
Copy the code The 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"




string




The above POST address is not followed by / as when requesting JSON data. Method name, and the SOAPAction method name also needs to be preceded by a namespace. So I modified the request header of XMLHttpRequest, modified the url and action accordingly, and finally returned the XML result normally: Hello World&Hello, Krime!
Later, I continued testing and found that when the request content type is application/json, SOAPAction can be completely ignored, but the / method name must be added after the url. Otherwise the server will not return data. When requesting text/xml, SOAPAction is required and must be preceded by a namespace. There cannot be a / method name after the url.
Finally, after summary, the code was changed to its final appearance:
Copy the code The 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, you need to add it after the url "/method name"
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); //Set the ContentType of the request header
xmlHttp.setRequestHeader('SOAPAction', options.namespace options.method); //Set the SOAPAction
xmlHttp.send(options.data); //Send parameter data
}

Request JSON data:
Copy code The 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 code The code is as follows:

window.onload = function () {
var data = ''
' ''
''
'Krime'
'
'
'
'
'
';
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.
One thing to note is that when requesting JSON data, if the return type is DataTable, it will not work. It needs to be converted into a List<> of the corresponding data entity class and then returned.

In the process of solving the problem of returning XML, another solution was also found. During the specific operation, the ContentType is set to application/x-www-form-urlencoded. The data body does not use JSON or XML format SOAP package, but uses "arguement1=XXX&arguement2=XXX" similar to QueryString. This method simulates the HTTP POST format of form data, encoding each control value as a name=value pair and sending it out.

In this case, the page address also needs to be followed by /method name.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn