How to get label value which loads with javascript

自古美人都是妖i 提交于 2020-01-15 08:07:48

问题


I have a link like that. It's getting from instagram api.

http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b

How can I get this link from codebehind? I can take it with js but i can't get it after assign to label. I mean:

<script>
    function getURL(){
        document.getElementById('lblAccessToken').innerText = location.href;
    }
</script>

This js function is in body onload event. How can I reach this innerText value from codebehind?


回答1:


If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this

Markup

<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var myToken = GetHashParameterByName("access_token");
        $("#lblAccessToken").html( myToken );
    });

    function GetHashParameterByName(name) {    
        var match = RegExp('[#&]' + name + '=([^&]*)')
                .exec(window.location.hash);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));    
    }
</script>

You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things

  1. Pass the hash value to a jQuery ajax method and store it there.
  2. Grab the hash value and redirect to the same page after converting it to a querystring

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var myToken = GetHashParameterByName("access_token") || "";
        if(my_token !=== ""){
            window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
        }
    });

    function GetHashParameterByName(name) {    
        var match = RegExp('[#&]' + name + '=([^&]*)')
                .exec(window.location.hash);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));    
    }
</script>

Now at Page_Load, grab it like

string token = Request.QueryString["access_token"];

Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.



来源:https://stackoverflow.com/questions/10273423/how-to-get-label-value-which-loads-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!