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

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

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

添加“一般處理程序”,如下圖

650) this.width=650;" width="954" height="658" title="捕獲.PNG" style="width:606px;height:467px;float:left;" alt="220824766.png" src="http://img1.51cto.com/attachment/201310/220824766.png" />

2.編寫“Handler2.ashx”代碼,如下:

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 ProcessRequest(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.結果如下

650) this.width=650;" width="1200" height="536" title="捕獲.PNG" style="width:774px;height:378px;" alt="221523570.png" src="http://img1.51cto.com/attachment/201310/221523570.png" />

本文出自 “獨釣寒江雪” 博客,請務必保留此出處http://zhaojie.blog.51cto.com/1768828/1317940

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章