这里是AJAX的新手。 一直试图使用AJAX发送到我的数据库,但是无法正常工作。 在我的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();
}
}
我正在尝试使用AJAX和C#ASP.NET插入数据。 这是我的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 %> + "'}",
})
完整网址为http://localhost:1759/Room?Board='// roomcode'。
有什么问题吗?就像我把url放入AJAX函数一样? 提前谢谢!
编辑: 是否需要将数据类型设置为JSON?也是JSON的新手......
答案 0 :(得分:1)
试试这段代码:
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:强>
您将获得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 %> + "'}",
})
答案 1 :(得分:-1)
您需要将正确的网址传递给致电方法。
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url:"Room.aspx/saveMsg",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})