Run db query (sql server 2005) with ajax. Is it possible?

前端 未结 3 1102
庸人自扰
庸人自扰 2020-12-18 17:11

I never worked with ajax.

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 refreshin

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 17:27

    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.

    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();
              }
          }
      }
    }
    

    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
      }
    });
    

    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")
    }
    

提交回复
热议问题