简体   繁体   中英

How to execute jquery script before page load?

I need to execute javascript before Page load in ASP.NET application.

My function returns user location, and I would like to pass value to server side and load data based on location.

The problem is javascript function executes after page load.

Here is my code:

    $(function () {
        getLocation();
    });

in getLocation function I set hidden field value

$("#<%= HfLocation.ClientID %>").val(location);

in code behind I try to get value but it's always empty

protected void Page_Load(object sender, EventArgs e)
        {
            var location = HfLocation.Value;
        }

I need to execute javascript before Page load in ASP.NET application

This requirements makes no sense. Remember how ASP.NET works:

  1. A user request hits the web server
  2. The web server dispatches the request to ASP.NET engine.
  3. The ASP.NET engine instantiates the page and goes through the entire page lifecycle.
  4. The page is rendered as HTML and is sent to the client
  5. The client browser builds the DOM, runs client side javascript, ...

You see that it is impossible to have step 5 execute before step 3 (in which the Page_Load event executes).

使用JavaScript执行ajax回调以请求数据。

I need to execute javascript before Page load in ASP.NET application.

In that case, you will need to make two page requests. You can't do it with a single page request, since Page_Load() runs before the HTML+JS is even sent to the client.

Instead, have a mini-page that makes the JS call and then either does a postback to the current page, or (probably better), loads a new page. You can pass the location data either through a regular (non-server) form, or perhaps by setting a cookie from JS on the client, or encode it into the query string.

The second page/request will then have the data you need when it's Page_Load() event fires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM