heml Ajax 經過Asp.net訪問數據庫(以Sql Server爲例)

假設從數據庫提取數據,在html頁面中顯示:javascript

1,創建服務器後端處理程序html

添加「通常處理程序」,以下圖java

220824766.png

2.編寫「Handler2.ashx」代碼,以下:ajax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace WebApplication5
{
/// <summary>
/// Handler1 的摘要說明
/// </summary>
public class Handler1 : IHttpHandler
{
public void Proce***equest(HttpContext context)
{
//採用EF從數據庫中提取數據
WeatherDBEntities weatherDbcontext = new WeatherDBEntities();
var dataset = from data in weatherDbcontext.T_Station
select new { data.StationName, data.StationPosition, data.Lat, data.Lon };
JavaScriptSerializer tool = new JavaScriptSerializer();
context.Response.ContentType = "text/plain"; //字符串形式
context.Response.Write(tool.Serialize(dataset));//將字符串編碼爲JSON類型
//
//備註,要從javascript中傳參數的話,以下代碼,data就是傳遞的參數。而在本文件中,經過context.request("zipcode")來獲取
//如context.Response.Write(context.Request.Params["zipcode"]);
//            $.ajax({
//  url: "/api/getWeather",
//data: {
//  zipcode: 97201
//},
//  success: function( data ) {
//    $( "#weather-temp" ).html( "<strong>" + data + "</strong> degrees" );
//  }
//});
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

3.添加Html頁面:HtmlPage1.html數據庫

4.結果以下c#

221523570.png

相關文章
相關標籤/搜索