【问题标题】:validate username ajax and json and asp.net验证用户名 ajax 和 json 以及 asp.net
【发布时间】:2011-03-09 04:22:43
【问题描述】:

所以我是 json/ajax/jquery/webservices 的新手

我正在尝试创建一个加入页面,用户可以输入几个字母并获得有关用户名是否可用的即时反馈。

我有一个 html 文件 [用户前端] 和一个 asmx 网络服务,该网络服务会检查它所获得的任何文本是否存在 [它运行一个运行良好的存储过程]

我的 html 文件似乎没有调用我的网络服务。

我已经通过转到 asmx 页面并手动输入值来验证 Web 服务是否正常工作,它会为我返回 true 或 false。
一个问题是它似乎是在 XML 中返回它,而不是我在其中的 json

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

继续代码/标记!

我的 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>

我的 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}";
        }

    }
}

所以当我手动运行 asmx 文件但 html 页面没有调用它并且我的 asmx 文件没有返回数据时,存储过程就像我看到的那样工作......所以基本上它让我发疯了!

【问题讨论】:

    标签: c# jquery asp.net ajax web-services


    【解决方案1】:

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

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

    public bool GetUsernameAvailable(string username)
    {
       ...
       return (RetVal == 0) ? false : true;
    }
    

    上面会返回布尔值,你在你的调用函数中调用访问它作为j.d。例如,

    ...
    $ajax({
     ...
     success: function (j) {
        alert(j.d); // will alert either true or false
     }
    ...
    

    最后,在浏览器中导航到 asmx 端点将调用soap端点,您将始终获得xml请求-响应(这是因为ASP.NET脚本处理程序仅在请求为POST请求且内容类型为JSON)。调试此问题的正确方法是检查您在 Fiddler 等工具中的服务调用。

    【讨论】:

    • 哇,这完全有效……我有正确的 web.config,但我不明白它的服务会为我转换它[虽然这很合乎逻辑]。非常感谢!
    【解决方案2】:

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

    data :{'username':t.value }
    

    【讨论】:

      猜你喜欢
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2011-10-23
      相关资源
      最近更新 更多