如何使用jQuery调用C#Web服务以获得返回值

编程入门 行业动态 更新时间:2024-10-24 19:27:47
本文介绍了如何使用jQuery调用C#Web服务以获得返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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服务以获得返回值

本文发布于:2023-10-11 22:31:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   返回值   jQuery   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!