Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 验证用户名ajax、json和asp.net_C#_Jquery_Asp.net_Ajax_Web Services - Fatal编程技术网

C# 验证用户名ajax、json和asp.net

C# 验证用户名ajax、json和asp.net,c#,jquery,asp.net,ajax,web-services,C#,Jquery,Asp.net,Ajax,Web Services,所以我不熟悉json/ajax/jquery/webservices 我正在尝试创建一个连接页面,用户在其中键入几个字母,并立即获得有关用户名是否可用的反馈 我有一个html文件[用户前端],还有一个asmx Web服务,Web服务检查它得到的文本是否存在[它运行一个运行良好的存储过程] 我的html文件似乎没有调用我的Web服务 我已经通过转到asmx页面并手动输入值验证了webservice的有效性,它为我返回true或false。 一个问题是,它似乎是以XML格式返回,如下图所示,而不是以

所以我不熟悉json/ajax/jquery/webservices

我正在尝试创建一个连接页面,用户在其中键入几个字母,并立即获得有关用户名是否可用的反馈

我有一个html文件[用户前端],还有一个asmx Web服务,Web服务检查它得到的文本是否存在[它运行一个运行良好的存储过程]

我的html文件似乎没有调用我的Web服务

我已经通过转到asmx页面并手动输入值验证了webservice的有效性,它为我返回true或false。
一个问题是,它似乎是以XML格式返回,如下图所示,而不是以json格式返回

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://localhost">{"available": false}</string>

{“可用”:false}
接下来是代码/标记

我的html文件

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
        <script type="text/javascript">
    <!--

        $(document).ready(function () {
            var validateUsername = $('#validateUsername');
            $('#username').keyup(function () {
                var t = this;
                if (this.value != this.lastValue) {
                    if (this.timer) clearTimeout(this.timer);
                    validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif" height="16" width="16" /> checking availability...');
                    this.timer = setTimeout(function () {
                        $.ajax({
                            contentType: "application/json; charset=utf-8",
                            url: 'ValidateUser.asmx/GetUsernameAvailable',
                            data: '{username: "'+t.value + '"}',
                            dataType: 'json',
                            type: "post",
                            success: function (j) {
                                validateUsername.html('I willl have my logic in here for changing the html on the label to reflect success or failure!');
                            }
                        });
                    }, 200);

                    this.lastValue = this.value;
                }
            });
        });
//-->
        </script>

</head>
<body>
    <fieldset>
        <div>
                <label for="username">Username, valid: a-z.-_</label>
                <input type="text" name="username" value="" id="username" />
                <span id="validateUsername"></span>
        </div>
    </fieldset>
</body>
</html>

用户名,有效:a-z-_
我的asmx文件

<%@ WebService Language="C#" Class="ValidateUser" %>
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.Odbc;
using System.Web.Script.Serialization;
using System.Web.Script.Services; 
using UserSite.DataClasses;

[WebService(Description = "Web services to query Username availability.", Namespace = "http://localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ValidateUser: System.Web.Services.WebService
{

    [WebMethod(Description = "Gets the availability of a username.")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetUsernameAvailable(string username)
    {

        if (username == null)
        {
            username = "";
        }
        DbaseExecSpWithReturnValue Sproc = new DbaseExecSpWithReturnValue();
        Sproc.SetSp("sp_CheckUsernameAvailable");
        Sproc.AddParam(1);
        Sproc.AddParam("Username", SqlDbType.Char, username, 20);
        int RetVal = Sproc.Execute();
        Sproc.Close();
        if (RetVal == 0)
        {
            return @"{""available"": false}";
        }
        else
        {
            return @"{""available"": true}";
        }

    }
}

使用制度;
使用System.Web;
使用系统集合;
使用System.Web.Services;
使用System.Web.Services.Protocols;
使用系统数据;
使用System.Data.Odbc;
使用System.Web.Script.Serialization;
使用System.Web.Script.Services;
使用UserSite.DataClasses;
[WebService(Description=“查询用户名可用性的Web服务”,命名空间=”http://localhost")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[脚本服务]
公共类ValidateUser:System.Web.Services.WebService
{
[WebMethod(Description=“获取用户名的可用性。”)]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
公共字符串GetUserName可用(字符串用户名)
{
如果(用户名==null)
{
用户名=”;
}
DbaseExecSpWithReturnValue存储过程=新的DbaseExecSpWithReturnValue();
存储过程设置(“sp_CheckUserName可用”);
存储过程AddParam(1);
Sproc.AddParam(“用户名”,SqlDbType.Char,用户名,20);
int RetVal=Sproc.Execute();
存储过程关闭();
如果(RetVal==0)
{
返回@“{”可用“:false}”;
}
其他的
{
返回@“{”可用“:true}”;
}
}
}

因此,存储过程的工作原理与我手动运行asmx文件时看到的一样,但html页面没有调用它,我的asmx文件也没有返回数据。。。。。所以基本上这让我发疯了

我认为您的ajax调用的数据不正确。根据jquery文档: data选项可以包含形式为key1=value1&key2=value2的查询字符串,也可以包含形式为{key1:'value1',key2:'value2'}的映射。如果使用后一种形式,则在发送数据之前,使用jQuery.param()将数据转换为查询字符串。尝试在不发送日期的情况下使用ajax来测试是否可以调用WS,然后尝试以下操作

data :{'username':t.value }

您使用的是哪个版本的.NET?如果是3.5,那么请确保您在web.config中注册了ScriptHandlerFactory和ScriptModule-它们负责处理JSON请求

第二个问题是,在实际的服务实现中,您应该返回所需的对象,ASP.NET基础结构将处理JSON序列化—您不必输出实际的JSON数据。比如说,

public bool GetUsernameAvailable(string username)
{
   ...
   return (RetVal == 0) ? false : true;
}
...
$ajax({
 ...
 success: function (j) {
    alert(j.d); // will alert either true or false
 }
...
上面将返回布尔值,您可以在调用函数中以
j.d
的形式调用它。比如说,

public bool GetUsernameAvailable(string username)
{
   ...
   return (RetVal == 0) ? false : true;
}
...
$ajax({
 ...
 success: function (j) {
    alert(j.d); // will alert either true or false
 }
...

最后,在浏览器中导航到asmx端点将调用soap端点,您将始终得到xml请求响应(这是因为只有当请求为POST请求且内容类型为JSON时,ASP.NET脚本处理程序才会执行JSON序列化)。正确的调试方法是检查您的服务调用工具,如Fiddler。

哇,这完全奏效了。。。我有正确的web.config,但我不知道服务会为我转换它[这是合乎逻辑的]。非常感谢你!