【问题标题】:how to save data in database using jquery如何使用jquery将数据保存在数据库中
【发布时间】:2013-11-01 18:05:43
【问题描述】:

我是 jquery 的新手。我经常用 c# 编写代码,现在我必须使用 jquery。我知道基本的jquery。 jquery只有几个功能。但现在我想做一些提前的事情。我想使用 jquery 从我的 asp.net 页面保存更新删除 sql server 中的数据。我为此尝试了一个 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";

    }

请告诉我该怎么做。

【问题讨论】:

  • 我猜你的代码很安静。你在javascript控制台中遇到任何错误吗??
  • “不工作”是什么意思?什么都没发生?您在控制台中有任何错误吗?尝试在您的方法中放置一个断点以查看它是否被调用。
  • @Polaris878 看看我是 jqeury 的新手,我对此一无所知,请告诉我如何查看错误以及我必须做什么
  • 原来你可以做到this question包含一篇文章和一些例子。
  • 我确实检查了第 7 行。我告诉您该行有错误,并为您提供了修复程序。现在是时候检查自己的代码了。

标签: jquery asp.net sql-server


【解决方案1】:

您的 Jquery 似乎没问题。 只要确保你的方法被调用。您可以添加断点并调试您的 c# 方法。

在你的 C# 代码中

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

我猜你缺少“into”关键字。

您还可以使用“调试器”关键字调试 jquery,并确保取消选中 IE-->Internet 选项-->高级-->浏览下的禁用脚本调试选项。

【讨论】:

    【解决方案2】:

    我已经对此进行了测试,并且可以正常工作:

    Default2.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>
    

    Default2.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";
            }
        }
    }
    

    【讨论】:

    • 我试试这个,但它在控制台 HTTP/1.1 500 内部服务器错误中给了我这个错误
    • 您是否完全调试过代码以查看您遇到的确切错误?可能就像错误的连接字符串一样简单。
    【解决方案3】:
    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>
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 2013-01-30
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多