记录已添加到数据库中,但使用Asp.net ajax

时间:2018-12-23 11:31:05

标签: asp.net ajax asp.net-mvc

记录添加成功。添加记录警报消息后,应在ajex成功函数中显示记录添加成功。但是未显示警报消息,我可以在控制台上看到错误。如何从Page_Load返回JSON结果 控制台显示错误

 <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>

    </title></head>
    <body>
        <form method="post" action="./insert.aspx" id="form1">
    <div class="aspNetHidden">
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="zTrrqKI/DheoFwp4sc62RwzP0iY7axSftHzvJzZCC41CzVd9kYfD4XJIyas1nyNOAlwAs0DfeNlb18I4G2QbZ+NkGfH792zp/tKY3N+cROg=" />
    </div>

    <div class="aspNetHidden">

        <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="F80457EB" />
    </div>
        <div>

        </div>
        </form>
    </body>
    </html>

asp.net的表单设计

<form  id="frmProject" runat="server">
            <div>
                <label class="form-label">First Name</label>     
               <input type="text" id="fname" class="form-control"  />
            </div>
            <div class="form-group" align="left">
             <label class="form-label">Age</label>
                <input type="text" id="age" class="form-control"  />
            </div>
            <div> 
               <input type="button" id="b1" value="add" class="form-control" onclick="addProject()" />

            </div>
        </form>

Ajax通过将数据发送到insert.aspx页面

   <script>
             function addProject() {
            $.ajax({
                type: 'POST',
                url: 'insert.aspx',
                dataType: 'JSON',
                data: {fname: $('#fname').val(), age: $('#age').val()},
                success: function (data) {
                  alert("suceess");
                },
                error: function (xhr, status, error) {

                    console.log(xhr.responseText);
                }
            });

        }     
    </script>

insert.aspx页面

SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
        protected void Page_Load(object sender, EventArgs e)
        {
            string fname = Request.QueryString["fname"];
            string age = Request.QueryString["age"];
            string sql = "insert into record values('" + fname + "','" + age+ "')";
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Write("success");
            con.Close();         
        }

1 个答案:

答案 0 :(得分:0)

尝试使用Request.Form而不是Request.QueryString

string fname = Request.Form["fname"];
string age = Request.Form["age"];