解决方法
正如
MarkusQ所说,不可能直接执行此操作,但您可以调用Web服务或页面方法来执行数据库查询并将结果返回给客户端.
对于页面方法这样的事情(这是我的头脑和未经测试.我也假设您正在使用asp.net 3.5)
public partial class _Default : Page { [WebMethod] public static string PerformDatabaseQuery() { using (sqlConnection con = new sqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString) { using (sqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT records FROM myTable"; cmd.CommandType = CommandType.Text; con.Open(); sqlDataReader reader = cmd.ExecuteReader(); StringBuilder sb = new StringBuilder(); while (reader.Read()) { sb.Append((string)reader["records"]); //May want to do some other formatting here } return sb.ToString(); } } } }
$.ajax({ type: "POST",url: "Default.aspx/PerformDatabaseQuery",data: "{}",contentType: "application/json; charset=utf-8",dataType: "json",success: function(result) { //Do something with the returned data } });
您可以使用JavaScript和在ScriptManager控件上设置EnablePageMethods = true时生成的JavaScript代理类来调用它.
function CallPerformDatabaseQuery() { PageMethods.PerformDatabaseQuery(onSuccess,onFailed); } function onSuccess(result,userContext,methodName) { // Do something with returned data } function onFailed(error,methodName) { alert("An error occurred") }