简体   繁体   English

使用ASP.NET,C#和jQuery发送到数据库

[英]Send to database using ASP.NET, c# and jQuery

New to AJAX here. 这是AJAX的新功能。 Been trying to send to my database using AJAX but is is not working. 一直在尝试使用AJAX发送到我的数据库,但无法正常工作。 In my aspx.cs: 在我的aspx.cs中:

[WebMethod]
    public static void saveMsg(string roomCode, string userName, string msg)
    {
        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LBConnectionString"].ConnectionString))
        {
            SqlCommand cmd = con.CreateCommand();

            cmd.CommandText = "INSERT into chatTable(roomCode, uName, msg) VALUES (" + roomCode + ", '" + userName + "', + '" + msg + "')";
            cmd.Connection = con;
            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();
        }
    }

I am trying to insert data using AJAX and C# ASP.NET. 我正在尝试使用AJAX和C#ASP.NET插入数据。 This is my aspx file 这是我的aspx文件

$.ajax({
                    type:'POST',
                    contectType: "application/json; charset=utf-8",
                    dataType: "json",
                    url:"Room.aspx?Board='" + roomCode + "'",
                    data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
                })

The full url is http://localhost:1759/Room?Board= '//roomcode'. 完整网址是http:// localhost:1759 / Room?Board = '// roomcode'。

Is there anything that went wrong? 有什么问题吗? Like how I put the url into the AJAX function? 就像我将网址放入AJAX函数一样? Thanks in advance! 提前致谢!

EDIT: Is it needed to put data type as JSON? 编辑:是否需要将数据类型作为JSON? New to JSON too... JSON的新手...

Try this code : 试试这个代码:

Javascript : Javascript:

function Getpath() {
if (!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var Domainpath = window.location.origin + "/";
if (Domainpath.indexOf("localhost") == -1) {
    return Domainpath;
}
else {
    return Domainpath;
}
}

Ajax: 阿贾克斯:

You will get the path in Getpath() Method . 您将在Getpath() Method获取路径。

var path = Getpath();
$.ajax({
                type:'POST',
                contectType: "application/json; charset=utf-8",
                dataType: "json",
                url: path +"Room.aspx?Board='" + roomCode + "'",
                data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
            })

You Need to Pass correct URL to call method. 您需要传递正确的URL来调用方法。

$.ajax({
       type:'POST',
       contectType: "application/json; charset=utf-8",
       dataType: "json",
       url:"Room.aspx/saveMsg",
       data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
   })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM