简体   繁体   English

传递参数jquery.load

[英]Passing parameter jquery.load

I am trying to load a template to a given DIV in my main .html file. 我正在尝试将模板加载到主.html文件中的给定DIV中。 I am trying to use jquery: 我正在尝试使用jQuery:

$('#Selected').load("template.html",{REQUIREDID:PARENTID})

The template loads correctly but I am unable to pass the variable and use it in the template. 模板正确加载,但是我无法传递变量并在模板中使用它。 For example <div>"requiredid"</div> How can I read the parameter that I am passing when I load the template 例如<div>"requiredid"</div>加载模板时如何读取传递的参数

Thanks. 谢谢。

You should do like this: 您应该这样做:

GET: 得到:

$('#Selected').load("template.html?requiredid=VALUE_TO_PASS");

POST: 开机自检:

$('#Selected').load("template.html",{requiredid=VALUE_TO_PASS});

Add following javascript method inside template.html to read the query parameters: template.html添加以下javascript方法以读取查询参数:

 function GetURLParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) 
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) 
            {
                return sParameterName[1];
            }
        }
    }​

and use it like: 并像这样使用它:

$('#someDivId').html(GetURLParameter('requiredid'));

I hope, It will help. 我希望,这会有所帮助。

You need it as GET parameter and access it with window.location.search as you can see here How to get "GET" request parameters in JavaScript? 您需要它作为GET参数,并通过window.location.search访问它,如您在此处看到的如何在JavaScript中获取“ GET”请求参数?

Or in a more better way: Place JavaScript code inside the template.html and use global variables from there. 或者,以一种更好的方式:将JavaScript代码放在template.html然后从那里使用全局变量。 If the template.html is included in your div container, you can run inside this file JavaScript code as it would be in the main template file from where you called the $.load function. 如果template.html包含在div容器中,则可以在此文件JavaScript代码中运行,就像在调用$.load函数的主模板文件中一样。 So, in other words: The scope is the same. 因此,换句话说:范围是相同的。 Inform yourself about JavaScript scopes. 通知自己有关JavaScript范围的信息。

Edit: That´sa typically angular/react use case. 编辑:这是一个典型的角度/反应用例。 Consider to use on of these MVVM JavaScript frameworks. 考虑在这些MVVM JavaScript框架上使用。

You have to return the Value for "requiredid" from the Server and store it in a variable. 您必须从服务器返回“ requiredid”的值并将其存储在变量中。 You can then access it in your Callbackfunction after load is completed. 加载完成后,您便可以在Callback函数中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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