传递参数jquery.load

时间:2016-10-19 13:19:53

标签: javascript jquery html

我正在尝试将模板加载到主.html文件中的给定DIV。我正在尝试使用jquery:

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

模板正确加载但我无法传递变量并在模板中使用它。例如<div>"requiredid"</div> 如何在加载模板时读取我传递的参数

感谢。

3 个答案:

答案 0 :(得分:1)

你应该这样做:

获取:

ng-repeat

发表:

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

$('#Selected').load("template.html",{requiredid=VALUE_TO_PASS});中添加以下javascript方法以读取查询参数:

template.html

并使用它:

 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];
            }
        }
    }​

我希望,这会有所帮助。

答案 1 :(得分:1)

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?

Or in a more better way: Place JavaScript code inside the template.html and use global variables from there. 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. So, in other words: The scope is the same. Inform yourself about JavaScript scopes.

Edit: That´s a typically angular/react use case. Consider to use on of these MVVM JavaScript frameworks.

答案 2 :(得分:0)

You have to return the Value for "requiredid" from the Server and store it in a variable. You can then access it in your Callbackfunction after load is completed.