如何使用jquery在数据库中保存数据

8xiog9wr  于 2022-12-12  发布在  jQuery
关注(0)|答案(3)|浏览(211)

我是jquery的新手。我经常用C#编写代码,现在我必须使用jquery。我知道jquery的基本知识。只是jquery的一些功能。但是现在我想做一些高级的事情。我想使用jquery保存、更新、删除我的www.example.com页面中sql server中的数据asp.net。我尝试了一个jquery代码,但是它不起作用。我不能得到什么是错误的,我在哪里出错。这是我的代码jquery,我正在使用

<script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json;charset=utf-8",
                    url: 'Default2.aspx/InsertMethod',
                    data: "{'username':'" + document.getElementById('txtusername').value + "','password':'" + document.getElementById("txtpassword").value + "'}",
                    async: false,
                    success: function (response) {
                        $('#txtusername').val('');
                        $('#txtpassword').val('');
                        alert("record has been saved in database");

                    },
                    error: function () {
                    console.log('there is some error');
                    }

                });

            });

        });

我用C#代码创建了一个web方法,在这里我编写了在sql server中保存数据的代码,并在jquery中调用了该web方法。但这段代码不起作用。以下是我的C#代码

[WebMethod]
    public static string InsertMethod(string username, string password)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("insert jquerydata values('" + username + "','" + password + "'", con);
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        con.Close();
        return "true";

    }

请告诉我怎么做。

cnh2zyt3

cnh2zyt31#

你的Jquery看起来很好。只要确保你的方法被调用了。你可以添加一个断点并调试你的C#方法。
在C#代码中

SqlCommand cmd = new SqlCommand("insert jquerydata values('" + username + "','" + password + "'", con);

我猜你漏掉了“into”这个关键词。
您也可以使用“debugger”关键字调试您的jquery,并确保在IE--〉Internet选项--〉高级--〉浏览下取消选中禁用脚本调试选项。

zzwlnbp8

zzwlnbp82#

我已经测试过了,它很有效:

默认值为2.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SO19542105: how to save data in database using jquery</title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#Button1").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "Default2.aspx/InsertMethod",
                    data: "{'username':'" + $("#txtusername").val() + "', 'password':'" + $("#txtpassword").val() + "'}",
                    async: false,
                    success: function (response) {
                        $("#txtusername").val("");
                        $("#txtpassword").val("");
                        alert("record has been saved in database");
                    },
                    error: function () {
                        console.log("there is some error");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="text" id="txtusername" placeholder="username" />
    <input type="password" id="txtpassword" placeholder="password" />
    <input type="button" id="Button1" value="OK" />
</body>
</html>

默认值为2.aspx.cs

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

namespace SO19542105
{
    public partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string InsertMethod(string username, string password)
        {
            using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO jquerydata(username, password) VALUES(@username, @password)";
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return "true";
        }
    }
}
emeijp43

emeijp433#

Write Static method in C# i.e. in aspx.cs page to insert data

[WebMethod]
    public static void AddRecord(string username, string password)
    {
        //SIMPLE SQL QUERY INSERT INTO
        {
            using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO jquerydata(username, password) VALUES(@username, @password)";
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return "true";
        }
        }
    }


create a html to accept two fields and insert data on click of button

<script src="3.2.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#Button1").on('click', function (e) {

            var userDetails = {
            username:$('#txtusername').val(),
            password: $('#txtpassword').val()
            };

            $.ajax({
                type: "POST",
                url: "pagename.aspx/AddRecord",
                data: JSON.stringify(userDetails),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnErrorCall
            });

            function OnSuccess(response) {
                var result = response.d;
                if (result == "success") {
                    $("#msg").html("New record addded successfully  :)").css("color", "green");
                }

            }

            function OnErrorCall(response) {
                $("#msg").html("Error occurs  :(").css("color", "red");
            }

        });

    });

</script>


<form id="form1">
    <div id="Tree">
       <input type="text" id="txtusername" placeholder="username" />
    <input type="password" id="txtpassword" placeholder="password" />
    <input type="button" id="Button1" value="OK" />
    </div>
</form>

相关问题