• 前后端分离(二)


    一、数据库city

    一张表cities,四个字段pName、cName、cNote、cImage

    二、JavaScript基础

    1、获取与设置元素的value值

    常用的<input type="text" />,<textarea>等文本框的value属性就是输入的值,DOM中通过:

    document.getElementById("id").value;

    来获取与设置id那个元素的值,例如:

    //设置id="province"的value的值为“广东”;

    document.getElementById("province").value="广东";

    //获取id="province"的value的值;

    var v=document.getElementById("province").value;

    2、获取与设置元素的innerHTML属性值

    常用的<div>,<span>等元素的innerHTML属性就是显示的值,DOM中通过:

    document.getElementById("id").innerHTML;

    来获取与设置id那个元素的值,例如:

    //设置id="msg"的innerHTML的值为“广东”;

    document.getElementById("msg").innerHTML="广东";

    //获取id="msg"的innerHTML的值;

    var v=document.getElementById("msg").innerHTML;

    三、JSON基础

    把一个对象转为JSON格式的字符串成为对象的序列化,一个对象只有序列化成一个字符串后才能在网络上传输。反过来,一个接收到JSON字符串必须转化为一个对象才能在程序中使用,这个过程称为JSON字符串反序列化。

    四、DEMO

    简述:这个DEMO实现的功能是在前端页面点击提交按钮,前端页面将要提交的数据转化为JSON格式,然后通过Ajax将JSON数据传输到后台,后接受到数据之后将JSON数据字符串反序列化为对象,再插入数据库,如果插入成功再在前端页面上打印出插入成功的字样。

    client.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Ajax</title>
        <script language="javascript">
            var http = null;
            function getHttp() {
                //获取XMLHttpRequest对象
                var http = null;
                try {
                    if (window.ActiveXObject)
                        http = new ActiveXObject("Microsoft.XMLHTTP");
                    else if (window.XMLHttpRequest)
                        http = new XMLHttpRequest();
                    else
                        alert('Getting XMLHttpRequest faild');
                }
                catch (exp) {
                    alert(exp.description);
                }
                return http;
            }
    
            function process() {
                if (http.readyState == 4) {
                    //获取服务器响应,显示结果
                    document.getElementById("msg").innerHTML = http.responseText;
                }
            }
    
            function getDateTime() {
                try {
                    //获取XMLHttpRequest对象
                    if (http == null) {
                        http = getHttp();
                    }
    
                    http.onreadystatechange = process;
                    //获取数据
                    var obj = new Object();
                    obj.province = document.getElementById("province").value;
                    obj.city = document.getElementById("city").value;
                    var s = JSON.stringify(obj);
                    //s = "&s="+s;
                    s = encodeURI(s);
                    s = encodeURI(s); //两次编码
                    //发送数据
                    http.open("GET", "server.ashx?&s=" + s + "&rnd=" + Math.random().toString(), true);
                    //http.open("POST", "server.ashx?&rnd=" + Math.random().toString(), true);
                    //设置数据格式
                    //http.setRequestHeader("content-Type", "application/json");
                    http.send(null);
    
                }
                catch (exp) {
                    alert(exp.description);
                }
            }
        </script>
    
    </head>
    <body>
        省份<input type="text" id="province" value="广东" style="50px" />
        城市<input type="text" id="city" value="深圳" style="50px" />
        <input type="submit" value="提交" onclick="getDateTime()"><br/>
        <span id="msg"/>
    </body>
    </html>

    server.ashx

    <%@ WebHandler Language="C#" Class="DEMO.server" Debug="true" %>
    using System;
    using System.Web;
    using System.Data;
    using System.Data.SqlClient;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace DEMO
    {
        public class server : IHttpHandler
        {
            private SQLHelper sqlhelper = null;
            //初始化
            public server()
            {
                sqlhelper = new SQLHelper(); 
            }
            
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
            public void ProcessRequest(HttpContext context)
            {
                //接收s
                String s=context.Request.QueryString["s"];
                //context.Response.ContentType = "application/json";
                //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //using (var reader = new System.IO.StreamReader(context.Request.InputStream))
                //{
                //    String s = reader.ReadToEnd();
    
                //    if (!string.IsNullOrEmpty(s))
                //    {
                //        //业务处理
                //    }
                //}
    
                
                //String s = context.Request.QueryString["s"];
                s = System.Web.HttpUtility.UrlDecode(s);
                //将json字符串转换为对象
                //JObject jObject = (JObject)JsonConvert.DeserializeObject(s);
                //JArray jar = JArray.Parse(jObject["RTDataSets"].ToString());
                JObject jObject = JObject.Parse(s);
          
                //接收province参数
                String p = (string)jObject["province"];
    
                //接收city参数
                String c = (string)jObject["city"];
                //context.Response.Clear();
                //context.Response.ContentType = "text/plain";
                //context.Response.Write(p + " " + c);
                //context.Response.Flush();
                if (Insert(p, c))
                {
                    context.Response.Write("增加("+p+","+c+")成功!"); 
                }
                else
                {
                    context.Response.Write("增加(" + p + "," + c + ")失败!"); 
                }
            }
            //插入函数
            public bool Insert(string pName,string cName)
            {
                bool flag = false;
                string sql = "insert into cities(pName,cName) values(@pName,@cName)";
                SqlParameter[] para = new SqlParameter[]{
                new SqlParameter("@pName",pName),
                new SqlParameter("@cName",cName)
                };
                int res = sqlhelper.ExecuteNonQuery(sql, para);
                if (res > 0)
                {
                    flag = true;
                }
                return flag;
                
            }
    
    
        }
    }

    SQLHelper.cs

    /* 
     * author :  H
     * time: 2015/5/30 16:50:04 
     * explain  : 数据库助手类
     */
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace DEMO
    {
        public class SQLHelper
        {
            private SqlConnection conn = null;
            private SqlCommand cmd = null;
            private SqlDataReader sdr = null;
            public SQLHelper()
            {
                string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
                conn = new SqlConnection(connStr);
            }
            private SqlConnection GetConn()
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                return conn;
            }
    
            /// <summary>
            /// 执行带参数的SQL增删改语句
            /// </summary>
            /// <param name="sql">增删改SQL语句</param>
            /// <param name="para">参数集合</param>
            /// <returns></returns>
            public int ExecuteNonQuery(string sql, SqlParameter[] para)
            {
                int res;
                using (cmd = new SqlCommand(sql, GetConn()))
                {
                    cmd.Parameters.AddRange(para);
                    res = cmd.ExecuteNonQuery();
                }
                return res;
            }
    
            /// <summary>
            /// 执行带参数的SQL查询
            /// </summary>
            /// <param name="sql">SQL语句</param>
            /// <param name="para">参数集合</param>
            /// <returns></returns>
            public DataTable ExecuteQuery(string sql, SqlParameter[] para)
            {
                DataTable dt = new DataTable();
                cmd = new SqlCommand(sql, GetConn());
                cmd.Parameters.AddRange(para);
                using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    dt.Load(sdr);
                }
                return dt;
            }
        }
    }
    
    数据库已经在文章的开头给出这里不再赘述。


  • 相关阅读:
    16日彻底去除安卓应用的内置广告
    配台600元的主机套装 自己组装 全新
    带记录功能的计算器
    华为8812 进入工程模式 和打电话黑屏问题
    买平板 四核 500~600左右对比
    querySelector()方法
    Javascript实例教程:querySelector()方法接受一个CSS查询并返回匹配模式的第一个子孙元素,如果没有匹配的元素则返回null。
    Android实用代码七段(二)
    Android实用代码七段(三)
    Firebug入门指南
  • 原文地址:https://www.cnblogs.com/haxianhe/p/9271210.html
Copyright © 2020-2023  润新知