ajax基础

Posted 游称

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax基础相关的知识,希望对你有一定的参考价值。

ajax:
一般处理程序(数据接口):ashx

跨语言传递数据:

xml:

 结构不清晰
 代码量比较大
 查找起来比较费事
 非面向对象结构

json:

 结构清晰
 代码量相对较小
 面向对象的处理解析方式,查找数据很简单
 

键值对
 {"key1":"value","key2":"value"}
 
 多个对象的json
 [{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]

 

下面公用的实体类、数据访问类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

/// <summary>
/// user 的摘要说明
/// </summary>
public class user
{
    SqlConnection conn = null;
    SqlCommand cmd = null;
    public user()
    {
        conn = new SqlConnection("server=.;database=data0928;user=sa;pwd=123");
        cmd = conn.CreateCommand();
    }
    public string username { get; set; }
    public string nickname { get; set; }
    public string password { get; set; }
    public bool sex { get; set; }
    public DateTime birthday { get; set; }
    public string nation { get; set; }
    public string Class { get; set; }

    public int age {

        get {
            int a;
            a = DateTime.Now.Year - this.birthday.Year;
            return a;
        }
    
    }
    public string nationname {
        get {
            string end = "";
            if (this.nation == "n001")
            { end = "汉族"; }
            if (this.nation == "n002")
            { end = "苗族"; }
            if (this.nation == "n003")
            { end = "壮族"; }
            if (this.nation == "n004")
            { end = "彝族"; }

            return end;
        }
  
    }
    public string classname {
        get {
            string end = "";
            cmd.CommandText = "select *from class where classcode=\'"+this.Class+"\'";
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                dr.Read();
                end = dr["classname"].ToString();
            }

            conn.Close();
            return end;        
        }    
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

/// <summary>
/// userdata 的摘要说明
/// </summary>
public class userdata
{
    SqlConnection conn = null;
    SqlCommand cmd = null;

    public userdata()
    {
        conn = new SqlConnection("server=.;database=data0928;user=sa;pwd=123");
        cmd = conn.CreateCommand();
    }
    public user select(string uname)
    {
        user u = null;
        cmd.CommandText = "select*from users where username=\'"+uname+"\'";
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
            u = new user();
            u.username = dr["username"].ToString();
            u.nickname = dr["nickname"].ToString();
            u.password = dr["password"].ToString();
            u.sex = Convert.ToBoolean(dr["sex"]);
            u.birthday = Convert.ToDateTime(dr["birthday"]);
            u.nation = dr["nation"].ToString();
            u.Class = dr["class"].ToString();

        }

        conn.Close();
        return u;
    }

    public List<user> select(int count,int number)
    {
        List<user> ulist = new List<user>();
        cmd.CommandText = "select top "+count+" * from users where ids not in(select top "+((number-1)*count)+" ids from users)";
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                user u = new user();
                u.username = dr["username"].ToString();
                u.nickname = dr["nickname"].ToString();
                u.password = dr["password"].ToString();
                u.sex = Convert.ToBoolean(dr["sex"]);
                u.birthday = Convert.ToDateTime(dr["birthday"]);
                u.nation = dr["nation"].ToString();
                u.Class = dr["class"].ToString();

                ulist.Add(u);
            }
        }

        conn.Close();
        return ulist;
    }



}

 

例子一:实时加载判断,展示数据

aspx文件中:包含ajax的基本写法

<%@ 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.2.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <table style="width:100%; background-color:navy;color:white;text-align:center;">
            <tr>
                <td>密码</td>
                <td>昵称</td>
                <td>性别</td>
                <td>生日</td>
                <td>年龄</td>
                <td>民族</td>
                <td>班级</td>
            </tr>
            <tr style="background-color:gray;">
                <td id="t1"></td>
                <td id="t2"></td>
                <td id="t3"></td>
                <td id="t4"></td>
                <td id="t5"></td>
                <td id="t6"></td>
                <td id="t7"></td>
            </tr>
            
        </table>
    </div>
    </form>
</body>
</html>
<script>
    var t = document.getElementById("TextBox1");
    t.onkeyup = function () {
        var c = t.value;

        $.ajax({
            url:"ajax/bb.ashx",//请求提交服务端
            data: {"sd":c},//给服务端带的数据,可以没有,也可以多个
            type: "post",//数据传递的方式
            dataType: "json",//数据传递的格式
            success: function (s) {
                document.getElementById("Label1").innerHTML = s.hhh;
                if (s.ddd == "true")
                { document.getElementById("Label1").style.color = "green"; }
                else
                {
                    document.getElementById("Label1").style.color = "red";

                    document.getElementById("t1").innerHTML = s.password;
                    document.getElementById("t2").innerHTML = s.nickname;
                    document.getElementById("t3").innerHTML = s.sex;
                    document.getElementById("t4").innerHTML = s.birthday;
                    document.getElementById("t6").innerHTML = s.nation;
                    document.getElementById("t7").innerHTML = s.class;
                    document.getElementById("t5").innerHTML = s.age;
                }
            }
        });
    }


</script>

ashx中:

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

using System;
using System.Web;

public class bb : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string s = context.Request["sd"];
        user u = new userdata().select(s);

        string end="{\\"hhh\\":\\"用户名可用\\",\\"ddd\\":\\"true\\"}";
        if (u == null)
        { end = "{\\"hhh\\":\\"用户名可用\\",\\"ddd\\":\\"true\\"}"; }
        else
        { end = "{\\"hhh\\":\\"用户名已被占用\\",\\"ddd\\":\\"false\\",\\"password\\":\\"" + u.password + "\\",\\"nickname\\":\\"" + u.nickname + "\\",\\"sex\\":\\"" +( u.sex?"":"") + "\\",\\"birthday\\":\\"" + u.birthday.ToString("yyyy年MM月dd日") + "\\",\\"nation\\":\\"" + u.nationname + "\\",\\"class\\":\\"" + u.classname + "\\",\\"age\\":\\""+u.age+"\\"}"; }

        context.Response.Write(end);
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

例子二:展示多条数据,数据分页

aspx中:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="js/jquery-1.7.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width:100%;text-align:center;background-color:navy">
            <thead style="color:white;">
                <tr>
                    <td>用户名</td>
                    <td>密码</td>
                    <td>昵称</td>
                    <td>性别</td>
                    <td>生日</td>
                    <td>年龄</td>
                    <td>民族</td>
                    <td>班级</td>
                </tr>             
            </thead>
            <tbody id="tbody" style="background-color:white;">
                
            </tbody>
        </table>   
        当前第<span id="sp">1</span><input type="button" value="上一页" id="btn1" />
        <input type="button" value="下一页" id="btn2" />


    </div>
    </form>
</body>
</html>
<script>
    var pagecount = 3;
    var pagenumber = 1;

    load(pagecount, pagenumber);

    document.getElementById("btn1").onclick = function () {
        pagenumber--;
        load(pagecount, pagenumber);
    }
    document.getElementById("btn2").onclick = function () {
        pagenumber++;
        load(pagecount, pagenumber);
    }

    function load(count,number) {
        $.ajax({
            url: "ajax/load.ashx",
            data: {"count":count,"number":number},
            type:"post",
            dataType:"json",
            success: function (data) {
                document.getElementById("tbody").innerHTML = "";
                for (i in data)
                {
                    var end = "<tr>";
                    end += "<td>" + data[i].username + "</td>";
                    end += "<td>" + data[i].password + "</td>";
                    end += "<td>" + data[i].nickname + "</td>";
                    end += "<td>" + data[i].sex+ "</td>";
                    end += "<td>" + data[i].age + "</td>";
                    end += "<td>" + data[i].birthday + "</td>";
                    end += "<td>" + data[i].nation + "</td>";
                    end += "<td>" + data[i].class + "</td>";
                    end += "</tr>";

                    document.getElementById("tbody").innerHTML += end;
                }
                document.getElementById("sp").innerHTML = number;
            }


        });
    };



</script>

ashx中:

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

using System;
using System.Web;
using System.Collections.Generic;
using System.Collections;

public class load : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        int c = Convert.ToInt32(context.Request["count"]);
        int n = Convert.ToInt32(context.Request["number"]);
        string json = "[";
        int count = 0;
        List<user> ulist = new userdata().select(c,n);
        foreach (user u in ulist)
        {
            if (count > 0)
            { json += ","; }
            json += "{\\"username\\":\\""+u.username+"\\",\\"password\\":\\"" + u.password + "\\",\\"nickname\\":\\"" + u.nickname + "\\",\\"sex\\":\\"" +( u.sex?"":"") + "\\",\\"birthday\\":\\"" + u.birthday.ToString("yyyy年MM月dd日") + "\\",\\"nation\\":\\"" + u.nationname + "\\",\\"class\\":\\"" + u.classname + "\\",\\"age\\":\\""+u.age+"\\"}";
            count++;
        }

        json += "]";
        context.Response.Write(json);
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

以上是关于ajax基础的主要内容,如果未能解决你的问题,请参考以下文章

AJAX相关JS代码片段和部分浏览器模型

Javascript代码片段在drupal中不起作用

前端面试题之手写promise

Ajax 片段元标记 - Googlebot 未读取页面内容

执行AJAX返回HTML片段中的JavaScript脚本

[vscode]--HTML代码片段(基础版,reactvuejquery)