How to use jQuery to make a call to c# webservice to get return value
I want to use jQuery to make a call to a c# web service called c.ashx which checks whether that username is valid and returns an error message as a string.
What should I put for data: and content type: if the return value of the c# webservice is a string value?
jQuery.ajax({
type: "GET",
url: "/services/CheckUserName.ashx",
data: "",
contenttype: "",
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
I have created a .asmx file instead, but it doesn't get called by the jQuery. Is the following correct?
jQuery.validator.addMethod("UsernameCheck", function (value, element) {
jQuery.ajax({
type: "POST",
url: "/services/CheckUsername.asmx?CheckUsername",
data: '{ "context": "' + jQuery("#username").value + '"}',
contentType: 'application/json; charset=utf-8',
开发者_运维知识库 dataType: 'json',
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
});
Data should contain the parameters of the method you are calling in a web service. However, the ashx extension is for an HTTP Handler, which is not a good choice for this scenario. A web service should by used instead.
So if you were calling /services/LoginServices.asmx?CheckUserName
, and CheckUserName.asmx had a webmethod ValidateUser
such as
public string ValidateUser(string username)
then the data
attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
your contentType
should be application/json; charset=utf-8
, and dataType
should be "json"
.
Note that you're not going to call /services/CheckUserName.asmx
, the name of the method in the web service has to be appended to the webservice url, /services/LoginServices.asmx?CheckUserName
.
Also, you'll need to change your type
to "POST"
.
Here's a complete example:
$.ajax({
type: 'POST',
url: 'LoginServices.asmx/CheckUserName',
data: '{"username": "' + usernameValue + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}});
Hope this helps
The jQuery code wasn't working because it wasn't calling the webservice. I fixed this by creating a HTTP handler class and passing it the username. I changed the value for data: to the following and it passed the username entered by the user:
data: "username=" + jQuery("#username").val(),
精彩评论