运行数据库查询(SQL Server 2005中)与阿贾克斯。可能吗? [英] Run db query (sql server 2005) with ajax. Is it possible?
问题描述
我从来没有与阿贾克斯。
I never worked with ajax.
我需要知道是否可以使用Ajax的数据库(SQL Server 2005中)上运行一个查询。
I need to know if it is possible to use ajax to run a query on the db (sql server 2005).
我的目标是与刷新页面运行查询。
My target is to run a query with refreshing the page.
你有什么想法?
推荐答案
作为<一个href="http://stackoverflow.com/questions/598900/run-db-query-sql-server-2005-with-ajax-is-it-possible/598903#598903">MarkusQ说,这是不可能直接这样做,但你可以调用Web服务或页面方法来执行数据库查询,并将结果返回给客户端。
As MarkusQ has said, it is not possible to do this directly, but you can call a web service or page method to perform the database query and return the result to the client side.
像这样一个页面的方法(这是从我头顶和未经考验的。我也让你使用asp.net 3.5的假设)
Something like this for a Page Method (this is off the top of my head and untested. I'm also making the assumption you're using 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();
}
}
}
}
然后调用从客户端的页面的方法。我要在这里使用jQuery
then call the page method from the client side. I'm going to use jQuery here
$.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,当你设置生成的JavaScript代理类称之为的EnablePageMethods = TRUE
在的ScriptManager
控制。
You can call it using JavaScript and the JavaScript proxy class that is generated when you set EnablePageMethods = true
on the ScriptManager
control.
function CallPerformDatabaseQuery()
{
PageMethods.PerformDatabaseQuery(onSuccess,onFailed);
}
function onSuccess(result,userContext,methodName)
{
// Do something with returned data
}
function onFailed(error,userContext,methodName)
{
alert("An error occurred")
}
这篇关于运行数据库查询(SQL Server 2005中)与阿贾克斯。可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!