使用ajax将webmethod数据集公开到服务器端

时间:2014-03-17 16:07:42

标签: javascript ajax c#-4.0 webmethod

我正在尝试使用c#和javascript编写应用程序。我的应用程序所做的是从db(lat,lng)读取地理位置,所以我写了一个Web方法来检索数据。我写了一个页面方法来从我的方法访问数据集。我需要帮助来解析从pagemethod到我的地理位置函数(lat,lng)的数据。

网络方法

    [WebMethod]
    public static string GetData()
    {
        SqlConnection sqlcon = new SqlConnection("Data Source=.\\SQLExpress; Initial catalog=Loca8DB; Integrated Security = True");
        sqlcon.Open();
        SqlCommand cmd = new SqlCommand("Select * From GeoArea", sqlcon);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        sqlcon.Close();
        string json = JsonConvert.SerializeObject(ds);
        return json;
    }

// Pagemethod将数据集返回到服务器端

function PageMethod(fn,paramArray,successFn,errorFn){

// Can pass Zero parameters as well. In method call(), use []
//  Suggestion is you put the callbacks as a function in your Page
var pagePath = window.location.pathname;

//Create list of parameters in the form:  
//{"paramName1":"paramValue1","paramName2":"paramValue2"}  -> JSON Format
var paramList = '';
if (paramArray.length > 0) {
    for (var i = 0; i < paramArray.length; i += 2) {
        if (paramList.length > 0) paramList += ',';
        paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
    }
}

paramList = '{' + paramList + '}';

//Call the page method  
$.ajax({
    type: "POST",
    url: pagePath + "/" + fn,
    contentType: "application/json; charset=utf-8", // Default to this type in case of JSON return types
    data: paramList,
    dataType: "json", // can be used for plaintext or for JSON
    success: successFn, // Callback when successful
    error: errorFn // Callback when an error
})
;

这是我需要帮助通过页面方法数据集粘贴到谷歌地图脚本

<script src="http://maps.googleapis.com/maps/api/js?key=bbbbbbbb&sensor=false">
</script>

<script>
function initialize() {
var mapProp = {
center: new google.maps.LatLng(51.5087, -0.120850),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap")
, mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script type="text/javascript" src="pagemethod.js"></script>

<script type="text/javascript">
function GetMyData() {
PageMethod("GetData", [], success, failed);
}
function success(msg) {
alert("Success" + msg.d);
}

function failed()
{
alert("Failed");
}

0 个答案:

没有答案