从页面加载的隐藏字段中抓取JS值

Grabbing JS values from hidden fields on page load

本文关键字:抓取 JS 字段 隐藏 加载      更新时间:2023-09-26

我正在尝试在。net中实现一些谷歌地图的东西。

然而,我正在努力使我的坐标到我的。net Google Maps控件。

我认为最简单的方法是使用HTML5地理定位API来获取当前位置的坐标,然后在我的。net代码中获取这些坐标并使用它们来居中地图。

我有以下JS代码:

    $(document).ready(function () {
            if (Modernizr.geolocation) {
                navigator.geolocation.getCurrentPosition(getCoords);
            }
            else {
                // no support
            }
            function getCoords(position) {
                $("#lat").val(position.coords.latitude);
                $("#long").val(position.coords.longitude);
            }
    });

这将纬度和经度的坐标放在各自的隐藏文本框中,#lat#long

现在,我想在。net代码后面的代码中获取它们。我试着这样做:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // some other code
    }
    // maps
    addStoreMap.enableDragging = false;
    addStoreMap.enableGoogleBar = false;
    // grab the coordinates here.
    decimal lat = Convert.ToDecimal(hdnLat.Value);
    decimal lng = Convert.ToDecimal(hdnLong.Value);
}

然而,这总是返回一个空值。我似乎无法将坐标值加载到。net代码中。当我通过JS提醒它们时,我得到了这些值。这是因为Page_Load事件发生在我的JS被执行之前吗?如果是这样,我该如何解决这个问题?

谢谢

document上的ready事件没有.preventDefault(),因此该行抛出错误。它从来没有达到geolocation代码。删除行:

e.preventDefault();

演示:http://jsfiddle.net/ThinkingStiff/mGj2W/

HTML:

<input id="lat" type="hidden" /><input id="long" type="hidden" />
<div id="result"></div>

脚本:

$( document ).ready( function () {
    if ( true ) { //modernizr check here
        navigator.geolocation.getCurrentPosition( getCoords );
    }
    else {
        // no support
    }
    function getCoords( position ) {
        $( '#lat' ).val( position.coords.latitude );
        $( '#long' ).val( position.coords.longitude );
        $( '#result' ).text( $( '#lat' ).val() + ', ' + $( '#long' ).val() );
    }
} );
输出:

39.583129, -124.4872483