ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动

Posted 王炜忠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动相关的知识,希望对你有一定的参考价值。

一、ajax验证表单元素规范正确与否

以用ajax来验证用户名是否被占用为例

1创建表单元素<input type="text" id="t">

2在js中用keyup事件来进行操作

3创建ajax格式和内容:格式:

$.ajax({

url:"哪一个服务端处理器",

data:{"自己起名",所需要传给处理器的数据},

type:"post",

dataType:"json",

success:function(aa){

//对处理器返回的值aa进行处理操作

},

error:function(){

alert("处理器连接失败");

}

});

4.代码示范

(1)建立linq

#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.17929
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;



[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="mydb")]
public partial class chinaDataContext : System.Data.Linq.DataContext
{
    
    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
    
  #region 可扩展性方法定义
  partial void OnCreated();
  partial void InsertChinaStates(ChinaStates instance);
  partial void UpdateChinaStates(ChinaStates instance);
  partial void DeleteChinaStates(ChinaStates instance);
  #endregion
    
    public chinaDataContext() : 
            base(global::System.Configuration.ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString, mappingSource)
    {
        OnCreated();
    }
    
    public chinaDataContext(string connection) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public chinaDataContext(System.Data.IDbConnection connection) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public chinaDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public chinaDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public System.Data.Linq.Table<ChinaStates> ChinaStates
    {
        get
        {
            return this.GetTable<ChinaStates>();
        }
    }
}

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ChinaStates")]
public partial class ChinaStates : INotifyPropertyChanging, INotifyPropertyChanged
{
    
    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
    
    private string _AreaCode;
    
    private string _AreaName;
    
    private string _ParentAreaCode;
    
    private bool _Root;
    
    private short _Zone;
    
    private string _NavigateURL;
    
    #region 可扩展性方法定义
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnAreaCodeChanging(string value);
    partial void OnAreaCodeChanged();
    partial void OnAreaNameChanging(string value);
    partial void OnAreaNameChanged();
    partial void OnParentAreaCodeChanging(string value);
    partial void OnParentAreaCodeChanged();
    partial void OnRootChanging(bool value);
    partial void OnRootChanged();
    partial void OnZoneChanging(short value);
    partial void OnZoneChanged();
    partial void OnNavigateURLChanging(string value);
    partial void OnNavigateURLChanged();
    #endregion
    
    public ChinaStates()
    {
        OnCreated();
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
    public string AreaCode
    {
        get
        {
            return this._AreaCode;
        }
        set
        {
            if ((this._AreaCode != value))
            {
                this.OnAreaCodeChanging(value);
                this.SendPropertyChanging();
                this._AreaCode = value;
                this.SendPropertyChanged("AreaCode");
                this.OnAreaCodeChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)]
    public string AreaName
    {
        get
        {
            return this._AreaName;
        }
        set
        {
            if ((this._AreaName != value))
            {
                this.OnAreaNameChanging(value);
                this.SendPropertyChanging();
                this._AreaName = value;
                this.SendPropertyChanged("AreaName");
                this.OnAreaNameChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ParentAreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false)]
    public string ParentAreaCode
    {
        get
        {
            return this._ParentAreaCode;
        }
        set
        {
            if ((this._ParentAreaCode != value))
            {
                this.OnParentAreaCodeChanging(value);
                this.SendPropertyChanging();
                this._ParentAreaCode = value;
                this.SendPropertyChanged("ParentAreaCode");
                this.OnParentAreaCodeChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Root", DbType="Bit NOT NULL")]
    public bool Root
    {
        get
        {
            return this._Root;
        }
        set
        {
            if ((this._Root != value))
            {
                this.OnRootChanging(value);
                this.SendPropertyChanging();
                this._Root = value;
                this.SendPropertyChanged("Root");
                this.OnRootChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Zone", DbType="SmallInt NOT NULL")]
    public short Zone
    {
        get
        {
            return this._Zone;
        }
        set
        {
            if ((this._Zone != value))
            {
                this.OnZoneChanging(value);
                this.SendPropertyChanging();
                this._Zone = value;
                this.SendPropertyChanged("Zone");
                this.OnZoneChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NavigateURL", DbType="VarChar(100)")]
    public string NavigateURL
    {
        get
        {
            return this._NavigateURL;
        }
        set
        {
            if ((this._NavigateURL != value))
            {
                this.OnNavigateURLChanging(value);
                this.SendPropertyChanging();
                this._NavigateURL = value;
                this.SendPropertyChanged("NavigateURL");
                this.OnNavigateURLChanged();
            }
        }
    }
    
    public event PropertyChangingEventHandler PropertyChanging;
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    protected virtual void SendPropertyChanging()
    {
        if ((this.PropertyChanging != null))
        {
            this.PropertyChanging(this, emptyChangingEventArgs);
        }
    }
    
    protected virtual void SendPropertyChanged(String propertyName)
    {
        if ((this.PropertyChanged != null))
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
#pragma warning restore 1591
View Code

(2)default页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.7.1.min.js"></script><%--引用jquery--%>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="text" id="t" /><span id="s"></span>
    </div>
    </form>
</body>
</html>
<script>
    $("#t").keyup(function () {//用keyup操作方式来验证
        var a = $(this).val();//先取值
        //1、将数据提交到服务端去
        $.ajax({
            url: "ajax/SelectUserName.ashx",//服务端处理器路径
            data: { "shuju": a },//将数据a提交到服务端去,”shuju“是自己随意起名
            type: "post",//规定提交方式,有post和get两种
            dataType: "json",//规定返回交互的数据类型,有”json“和”xml“。但是json比xml好用
            success: function (b) {//b为SelectUserName.ashx中返回的namejson的值
                if (b.has == "0") {
                    $("#s").text("恭喜,用户名能使用").css("color","blue");
                }
                else {
                    $("#s").text("抱歉,用户名已被使用").css("color","red");
                }
            },//sucess
            error: function () {//success不成功,会走这一步!!
                alert("服务器连接失败");
            }
        });//ajax
    });//keyup




</script>
View Code

(3)服务处理器SelectUserName.ashx页面,(建立在新建文件夹ajax的里面,与default平级)

<%@ WebHandler Language="C#" Class="SelectUserName" %>

using System;
using System.Web;
using System.Linq;

public class SelectUserName : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string name = context.Request["shuju"];//获取Default.aspx中提交的数据
       string namejson = "{\\"has\\":\\"0\\"}";//建立json,格式为{"key":"value","key":"value",..........}
       using (xinxiDataContext cnn = new xinxiDataContext())
       {
           var ss = cnn.Users.Where(r => r.UserName == name).AsEnumerable();//查询是否有该UserName,此处没有进行数据访问  此处需要引用using System.Linq;
           if (ss.Count() > 0)//如果有该UesrName,ss里面是有数据的,反之,没有
           {
               namejson = "{\\"has\\":\\"1\\"}";//修改namejson内容
           }
       }
       context.Response.Write(namejson);//将namejson返回出去
       context.Response.End();//关闭输出
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
View Code

 

二、ajax展示加载数据库数据

1、服务处理器的作用就是用含有json的数组把数据传出来,再在web窗体端对该数组进行处理。

含有json的数组的格式:[{"key1":"value1","key2":"value2"},{"key3":"value3"}........{"keyn":"value3"}]。

2、以数据库xinxi中Uers和Nation表为例

(1)建立linq。(xinxi.dbml)

#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.17929
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;



[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="xinxi")]
public partial class xinxiDataContext : System.Data.Linq.DataContext
{
    
    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
    
  #region 可扩展性方法定义
  partial void OnCreated();
  partial void InsertUsers(Users instance);
  partial void UpdateUsers(Users instance);
  partial void DeleteUsers(Users instance);
  partial void InsertNation(Nation instance);
  partial void UpdateNation(Nation instance);
  partial void DeleteNation(Nation instance);
  #endregion
    
    public xinxiDataContext() : 
            base(global::System.Configuration.ConfigurationManager.ConnectionStrings["xinxiConnectionString"].ConnectionString, mappingSource)
    {
        OnCreated();
    }
    
    public xinxiDataContext(string connection) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public xinxiDataContext(System.Data.IDbConnection connection) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public xinxiDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public xinxiDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
            base(connection, mappingSource)
    {
        OnCreated();
    }
    
    public System.Data.Linq.Table<Users> Users
    {
        get
        {
            return this.GetTable<Users>();
        }
    }
    
    public System.Data.Linq.Table<Nation> Nation
    {
        get
        {
            return this.GetTable<Nation>();
        }
    }
}

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Users")]
public partial class Users : INotifyPropertyChanging, INotifyPropertyChanged
{
    
    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
    
    private string _UserName;
    
    private string _Password;
    
    private bool _Sex;
    
    private string _NickName;
    
    private System.DateTime _Birthday;
    
    private string _Nation;
    
    private string _State;
    
    private EntityRef<Nation> _Nation1;
    
    #region 可扩展性方法定义
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnUserNameChanging(string value);
    partial void OnUserNameChanged();
    partial void OnPasswordChanging(string value);
    partial void OnPasswordChanged();
    partial void OnSexChanging(bool value);
    partial void OnSexChanged();
    partial void OnNickNameChanging(string value);
    partial void OnNickNameChanged();
    partial void OnBirthdayChanging(System.DateTime value);
    partial void OnBirthdayChanged();
    partial void OnNationChanging(string value);
    partial void OnNationChanged();
    partial void OnStateChanging(string value);
    partial void OnStateChanged();
    #endregion
    
    public Users()
    {
        this._Nation1 = default(EntityRef<Nation>);
        OnCreated();
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UserName", DbType="NVarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
    public string UserName
    {
        get
        {
            return this._UserName;
        }
        set
        {
            if ((this._UserName != value))
            {
                this.OnUserNameChanging(value);
                this.SendPropertyChanging();
                this._UserName = value;
                this.SendPropertyChanged("UserName");
                this.OnUserNameChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Password", DbType="NVarChar(20) NOT NULL", CanBeNull=false)]
    public string Password
    {
        get
        {
            return this._Password;
        }
        set
        {
            if ((this._Password != value))
            {
                this.OnPasswordChanging(value);
                this.SendPropertyChanging();
                this._Password = value;
                this.SendPropertyChanged("Password");
                this.OnPasswordChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Sex", DbType="Bit NOT NULL")]
    public bool Sex
    {
        get
        {
            return this._Sex;
        }
        set
        {
            if ((this._Sex != value))
            {
                this.OnSexChanging(value);
                this.SendPropertyChanging();
                this._Sex = value;
                this.SendPropertyChanged("Sex");
                this.OnSexChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NickName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)]
    public string NickName
    {
        get
        {
            return this._NickName;
        }
        set
        {
            if ((this._NickName != value))
            {
                this.OnNickNameChanging(value);
                this.SendPropertyChanging();
                this._NickName = value;
                this.SendPropertyChanged("NickName");
                this.OnNickNameChanged();
            }
        }
    }
    
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Birthday", DbType="DateTime NOT NULL")]
    public System.DateTime Birthday
    {
        get
        {
            return this._Birthday;
        }
        set
        {
            if ((this._Birthday != value))
            {
                this以上是关于ajax验证表单元素规范正确与否   ajax展示加载数据库数据    ajax三级联动的主要内容,如果未能解决你的问题,请参考以下文章

封装的ajax请求

Yii - ajax 加载的表单元素的用户端验证

我的 AJAX 查询未正确验证

在LayUI表单中,有AJAX方式来提交表单吗

jQuery 表单验证和 Ajax 提交的问题

codeigniter 中的 Ajax 表单验证