ASP.NET前台html頁面AJAX提交數據后台ashx頁面接收數據


摘要:最近在寫網站,好不容易弄好了需求又變了,沒錯企業的門戶網站硬要弄成后台管理系統一樣,沒辦法作為小工的我只能默默的改。前台HTML頁面需要提交數據到后台處理,又不能用form表單,於是乎研究了1天終於弄出來了。嘗試了好多種方法最后還是用ajax解決了好了廢話不多說了直接進入正題。

   

      實現的功能里面的數據提交保存到數據庫,同事對數據進行驗證,這是要實現的效果,由於cms的原因這里只能添加html頁面不能用aspx。

     1、頁面布局好了首先你要添加jquery文件(這個百度自己下載)在寫Ajax方法 前台是這樣的。你會發現我只是用按鈕提交的沒有用表單,因為下面要拼接表格

<div class="yjdjfm">
    <div class="yjdjfd"> 
        <ul>
            <li><span>儀檢名稱:</span><input id="txtyjneme" name="txtyjneme" type="text" value="" required="required"  oninvalid="setCustomValidity('必須填寫!');" oninput="setCustomValidity('');"  /><strong>*</strong><i class="yz_name" style="display:none; color:red;">請填寫儀檢名稱</i></li>
            <li><span>規格型號:</span><input id="txtyjxh" name="txtyjxh" type="text" value="" autofocus="autofocus" placeholder="" /><strong>*</strong><i class="yz_xh" style="display:none; color:red;">請填寫規格型號</i></li>
            <li><span>出廠編號:</span><input id="txtyjnumber" name="txtyjnumber" type="text" value="" /><strong>*</strong><i class="yz_bh" style="display:none; color:red;">請填寫設備編號</i></li>
        </ul>

        <ul style="float:right; margin-top:-122px;">
            <li><span>登記日期:</span><input id="txtyjdate" name="txtyjdate" type="text" value="" readonly /><strong>*</strong><i  style="color:#d0cfcf;">系統默認時間</i></li>
            <li><span>&nbsp;&nbsp;&nbsp;人:</span><input id="txtyjperson" name="txtyjperson" type="text" value="" /><strong>*</strong><i class="yz_person" style="display:none; color:red;">請填寫您的姓名</i></li>
            <li><span>聯系電話:</span><input id="txtyjphone" name="txtyjphone" type="number" value="" /><strong>*</strong><i class="yz_phone" style="display:none; color:red;">請正確填寫手機號碼</i></li>
        </ul>
    </div>
   <button class="yjdjtjan" id="btntj">添加記錄</button>

    <div style="clear:both;"></div>


    <div class="yjdjlist">
        <table id="tttab">
            <tr id="yjdjtrone">
                <td>序號</td>
                <td>儀檢名稱</td>
                <td>規格型號</td>
                <td>出廠編號</td>
                <td>登記日期</td>
                <td>&nbsp;&nbsp;&nbsp;</td>
                <td>聯系電話</td>
            </tr>
        </table></div>
</div>

 

     2、驗證數據Ajax提交

    <script type="text/javascript">
        function cheack()
        {
            var _yjname = $("#txtyjneme").val();//jQuery獲取文本框儀檢名稱值
            var _yjxh = $("#txtyjxh").val();
            var _yjbh = $("#txtyjnumber").val();
            var _yjperson = $("#txtyjperson").val();
            var _yjphone = $("#txtyjphone").val();
            if (_yjname == "") { $(".yz_name").css({ display: "block", float: "right" }); return false; } else { $(".yz_name").css("display","none") }
            if (_yjxh == "") { $(".yz_xh").css({ display: "block", float: "right" }); return false; } else { $(".yz_xh").css("display", "none") }
            if (_yjbh == "") { $(".yz_bh").css({ display: "block", float: "right" }); return false; } else { $(".yz_bh").css("display", "none") }
            if (_yjperson == "") { $(".yz_person").css({ display: "block", float: "right" }); return false; } else { $(".yz_person").css("display", "none") }
            if (!(/^1[34578]\d{9}$/.test(_yjphone)) && _yjphone.length == 11) { $(".yz_phone").css("display", "none"); return true;}else { $(".yz_phone").css({ display: "block", float: "right" }); return false;}}
             $(document).ready(function () {
            var d = new Date();
            var cs = 1;
            $("#txtyjdate").val(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate());
            $("#btntj").click(function () {
                if (cheack() == false) { return;}
                var _name = $("#txtyjneme").val();
                var _xh = $("#txtyjxh").val();
                var _number = $("#txtyjnumber").val();
                var _date = $("#txtyjdate").val();
                var _person = $("#txtyjperson").val();
                var _phone = $("#txtyjphone").val();
                like = window.confirm("請仔細核對信息再提交,提交了就無法更改");
                    if (like == true) {
                    
                    $.ajax({                         
                        type:"post",                  //提交方式
                        url: "{config.webpath}tools/submit_ajax.ashx",  //提交路徑
                        data:{name:_name,xh:_xh,bh:_number,date:_date,person:_person,phone:_phone},//參數
                        success: function (result, status)//成功函數
                        {
                            alert("數據庫保存成功!");
                            $("#tttab").append("<tr><td>" + cs + "</td><td>" + _name + "</td><td>" + _xh + "</td><td>" + _number + "</td><td>" + _date + "</td><td>" + _person + "</td><td>" + _phone + "</td></tr>");//拼接表格
                            cs++;
                            $("input[name='txtyjneme']").val("");
                            $("input[name='txtyjxh']").val("");
                            $("input[name='txtyjnumber']").val("");
                            $(".yjdjlist").css("display", "block");
                        },
                        error: function () { alert("添加失敗,程序異常!"); return; }
                    });
}
else { return; } }); }); </script>

 

  3、重點說一下這個ajax提交這里:

type提交的方法一般我都是用post,get提交數據多了就不行;

URL:提交的路徑以為提交到submit_ajax.ashx頁面所以不需要寫方法,它默認到submit_ajax頁面里的ProcessRequest()的方法中,之前我自己寫了方法也制定到這個方法上 但是很遺憾沒有獲取到值,如果提交aspx頁面就要寫到頁面的方法如:url: "{config.webpath}tools/submit_ajax.ashx/方法名",

data:數據參數,這邊的name,xh,bh要跟取值的時候對應,

我沒有寫dataType,因為我取值不做處理就不以一般的json傳值了,開始的時候我加了json發現到那邊取值有點麻煩(可能我方法不對);

4、來看一下后台

 public void ProcessRequest(HttpContext context)
        {
            
            var name = HttpContext.Current.Request["name"];
            var xh = HttpContext.Current.Request["xh"];
            var bh = HttpContext.Current.Request["bh"];
            var data = HttpContext.Current.Request["date"];
            var person = HttpContext.Current.Request["person"];
            var phone =HttpContext.Current.Request["phone"];
            string _sql = string.Format("insert into InstrumentCheck(Name,Modle,Number,Person,Phone) values('{0}','{1}','{2}','{3}','{4}')",name,xh,bh,person, phone);
            _sql.Replace("'", " ");
             ExecuteNonQuery(_sql);
        }
        public static string connectionStringgg = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        /// <summary>
        /// 插入數據
        /// </summary>
        /// <param name="sql">sql語句</param>
        /// <returns>影響的行數</returns>
        public void ExecuteNonQuery(string sql)
        {
                SqlConnection connection = new SqlConnection(connectionStringgg);
            if(connection.State==ConnectionState.Closed)
            {
                connection.Open();
            }
                
                SqlCommand cmd = new SqlCommand(sql, connection);
                 cmd.ExecuteNonQuery();

        }

 

你只要url指定這個頁面  它就會加載ProcessRequest(HttpContext context)這個方法;ajax傳的值用var類型來接收。這里我就不寫啥SqlDB類了。

5、添加一條成功的效果

添加2條拼接上去數據庫也保存了

新手上路,請各位大牛有緣見者多多指教不足或者錯的地方!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM