如何使用jQuery调用C#Web服务以获得返回值 [英] How to use jQuery to make a call to c# webservice to get return value
问题描述
我想使用jQuery调用名为c.ashx的c#Web服务,该服务检查用户名是否有效,并以字符串形式返回错误消息.
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.
如果c#Web服务的返回值是字符串值,我应该输入什么数据和内容类型?
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);
}
});
我创建了一个.asmx文件,但是jQuery并未调用它.以下正确吗?
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);
}
});
});
推荐答案
数据应包含您在Web服务中调用的方法的参数.但是,ashx扩展适用于HTTP处理程序,在这种情况下,这不是一个很好的选择.应该改为使用Web服务.
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.
因此,如果您正在呼叫/services/LoginServices.asmx?CheckUserName
,并且CheckUserName.asmx具有网络方法ValidateUser
,例如
So if you were calling /services/LoginServices.asmx?CheckUserName
, and CheckUserName.asmx had a webmethod ValidateUser
such as
public string ValidateUser(string username)
然后jQuery的data
属性为
then the data
attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
您的contentType
应该是application/json; charset=utf-8
,dataType
应该是"json"
.
请注意,您不会调用/services/CheckUserName.asmx
,必须将Web服务中方法的名称附加到Web服务网址/services/LoginServices.asmx?CheckUserName
.
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
.
此外,您需要将type
更改为"POST"
.
Also, you'll need to change your type
to "POST"
.
这是一个完整的例子:
$.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);
}});
希望这会有所帮助
这篇关于如何使用jQuery调用C#Web服务以获得返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!