最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - i can't access freemarker variables in external javascript file - Stack Overflow

programmeradmin2浏览0评论

i cant get the value of a freeMarker variable when i put my code in a external javascript file

here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:

<#import "../masterPage.html" as layout>
<@layout.masterPageLay bread1="my bread1" bread2="my bread2">

<#assign title="value 1"> 
<#assign subtitle="value 2"> 



<script>
function doAjaxPost() 
{
    var name= $('#name').val();
    var lastName= $('#lastName').val();



    var json = {"name" : name, "lastName" : lastName};
    console.log(json);

    var variableFreeMarker = "${freeMarkValue}";
    console.log('this value is: ' + variableFreeMarker); 

    $.ajax(
    {
        type: "POST",
        url: "myUrl",
        data: JSON.stringify(json), 

        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,

        beforeSend: function(xhr) 
                        {
                        xhr.setRequestHeader("Accept", "application/json");  
                        xhr.setRequestHeader("Content-Type", "application/json");  
                        },
        success: function(data) 
                {

                },
            error:function(data,status,er) { 
                alert("error: "+data+" status: "+status+" er:"+er);
            }
        /* error: function (xhr, ajaxOptions, thrownError) 
               {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
        }*/
    });
}

</script> 



    <form name="myform">
        Name in view:        <input type="text"  id="name" name="name">
        <br>
        Last Name in view:   <input type="text" id="lastName" name="lastName">
        <br>
        Show modify name in view:   <input type="text" id="modifyname" name="modifyname">
        <br>

        <input type="button" value="Add Users" onclick="doAjaxPost()">
    </form>

 <br>
 </@layout.masterPageLay>

but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script

<script src="../resources/js/scripts/myPageScript.js"></script> 

and this is my page that dont work

<#import "../masterPage.html" as layout>
    <@layout.masterPageLay bread1="my bread1" bread2="my bread2">

<#assign titulo="value 1"> 
<#assign subtitulo="value 2"> 

<script src="../resources/js/scripts/myPageScript.js"></script> 





    <form name="myform">
        Name in view:        <input type="text"  id="name" name="name">
        <br>
        Last Name in view:   <input type="text" id="lastName" name="lastName">
        <br>
        Show modify name in view:   <input type="text" id="modifyname" name="modifyname">
        <br>

        <input type="button" value="Add Users" onclick="doAjaxPost()">
    </form>

 <br>
 </@layout.masterPageLay>

this output in my chrome console "${freeMarkValue}" instead of the value of the variable

here are my controllers i'm processing the form using jquery ajax

@RequestMapping(value = "myForm", method = RequestMethod.GET)
    public String myForm(Model model) {



        model.addAttribute("freeMarkValue", "controll");

        return "myForm";
    }
@RequestMapping(value = "myForm", method = RequestMethod.POST)
    public @ResponseBody String getTags(@RequestBody final String json, Model model) 
    throws IOException 
    {
         ObjectMapper mapper  =  new ObjectMapper();

         User objetmapped =  mapper.readValue(json, User .class);

         User person  =  new User  iox();
         person.setName(objetmapped .getName());
         person.setLastName(objetmapped .getLastName());

       );



         model.addAttribute("freeMarkValue", "second controller value");

         return toJson(objetmapped );
    }

    private String toJson(User person) 
    {
        ObjectMapper mapper = new ObjectMapper();
        try 
        {
            String value = mapper.writeValueAsString(person);
            // return "["+value+"]";
            return value;
        } 
        catch (JsonProcessingException e) 
        {
            e.printStackTrace();
            return null;
        }
    }

i cant get the value of a freeMarker variable when i put my code in a external javascript file

here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:

<#import "../masterPage.html" as layout>
<@layout.masterPageLay bread1="my bread1" bread2="my bread2">

<#assign title="value 1"> 
<#assign subtitle="value 2"> 



<script>
function doAjaxPost() 
{
    var name= $('#name').val();
    var lastName= $('#lastName').val();



    var json = {"name" : name, "lastName" : lastName};
    console.log(json);

    var variableFreeMarker = "${freeMarkValue}";
    console.log('this value is: ' + variableFreeMarker); 

    $.ajax(
    {
        type: "POST",
        url: "myUrl",
        data: JSON.stringify(json), 

        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,

        beforeSend: function(xhr) 
                        {
                        xhr.setRequestHeader("Accept", "application/json");  
                        xhr.setRequestHeader("Content-Type", "application/json");  
                        },
        success: function(data) 
                {

                },
            error:function(data,status,er) { 
                alert("error: "+data+" status: "+status+" er:"+er);
            }
        /* error: function (xhr, ajaxOptions, thrownError) 
               {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
        }*/
    });
}

</script> 



    <form name="myform">
        Name in view:        <input type="text"  id="name" name="name">
        <br>
        Last Name in view:   <input type="text" id="lastName" name="lastName">
        <br>
        Show modify name in view:   <input type="text" id="modifyname" name="modifyname">
        <br>

        <input type="button" value="Add Users" onclick="doAjaxPost()">
    </form>

 <br>
 </@layout.masterPageLay>

but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script

<script src="../resources/js/scripts/myPageScript.js"></script> 

and this is my page that dont work

<#import "../masterPage.html" as layout>
    <@layout.masterPageLay bread1="my bread1" bread2="my bread2">

<#assign titulo="value 1"> 
<#assign subtitulo="value 2"> 

<script src="../resources/js/scripts/myPageScript.js"></script> 





    <form name="myform">
        Name in view:        <input type="text"  id="name" name="name">
        <br>
        Last Name in view:   <input type="text" id="lastName" name="lastName">
        <br>
        Show modify name in view:   <input type="text" id="modifyname" name="modifyname">
        <br>

        <input type="button" value="Add Users" onclick="doAjaxPost()">
    </form>

 <br>
 </@layout.masterPageLay>

this output in my chrome console "${freeMarkValue}" instead of the value of the variable

here are my controllers i'm processing the form using jquery ajax

@RequestMapping(value = "myForm", method = RequestMethod.GET)
    public String myForm(Model model) {



        model.addAttribute("freeMarkValue", "controll");

        return "myForm";
    }
@RequestMapping(value = "myForm", method = RequestMethod.POST)
    public @ResponseBody String getTags(@RequestBody final String json, Model model) 
    throws IOException 
    {
         ObjectMapper mapper  =  new ObjectMapper();

         User objetmapped =  mapper.readValue(json, User .class);

         User person  =  new User  iox();
         person.setName(objetmapped .getName());
         person.setLastName(objetmapped .getLastName());

       );



         model.addAttribute("freeMarkValue", "second controller value");

         return toJson(objetmapped );
    }

    private String toJson(User person) 
    {
        ObjectMapper mapper = new ObjectMapper();
        try 
        {
            String value = mapper.writeValueAsString(person);
            // return "["+value+"]";
            return value;
        } 
        catch (JsonProcessingException e) 
        {
            e.printStackTrace();
            return null;
        }
    }
Share Improve this question edited Feb 19, 2015 at 13:58 stackUser2000 asked Feb 19, 2015 at 13:40 stackUser2000stackUser2000 1,69511 gold badges32 silver badges56 bronze badges 4
  • If you think about what is going on you will see that it will never work. When it is in a separate static file (i.e. not subject to any server side processing) how can the freemarker variables possibly be replaced without also running the file myPageScript.js through the Freemarker engine? – Alan Hay Commented Feb 19, 2015 at 16:54
  • how can i run that file through the FreeMarker engine? i dont want o have my javascript code inside my view i just want to call ithe script – stackUser2000 Commented Feb 19, 2015 at 17:53
  • Consider adding the variables to the html file in a script element or as values in a hidden input field and keep the rest in a normal js file. Do not generate js sript through freemarker. I have seen this done and it is very difficult to code without errors as the IDE cannot format the code and check syntax, and secondly all the open braces { need to be doubled up which is loads in JS. – Goose Commented Feb 24, 2015 at 9:03
  • thanks @Goose can you give a example in answer of the firts solution you give me please you can use my code if you want.., i dont understand too good what you mean when you said: adding the variables to the html file in a script element – stackUser2000 Commented Feb 24, 2015 at 13:14
Add a ment  | 

1 Answer 1

Reset to default 4

You can move your variable into a script block in the html page.

<#import "../masterPage.html" as layout>
<@layout.masterPageLay bread1="my bread1" bread2="my bread2">

<#assign titulo="value 1"> 
<#assign subtitulo="value 2"> 

<script src="../resources/js/scripts/myPageScript.js"></script> 

<script>
    // This variable can be accessed from myPageScript.js
    var variableFreeMarker = "${freeMarkValue}";
</script>

<form name="myform">
    Name in view:        <input type="text"  id="name" name="name">
    <br>
    Last Name in view:   <input type="text" id="lastName" name="lastName">
    <br>
    Show modify name in view:   <input type="text" id="modifyname" name="modifyname">
    <br>

    <input type="button" value="Add Users" onclick="doAjaxPost()">
</form>


Or add it as a value of a hidden input etc..

<input type="hidden" id="myVal" value="${freeMarkValue}">

Your JS (in a seperate script) would then need to read the value for example using jQuery.

var aValue = $("#myVal").val();

I use the first method for mon stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.

发布评论

评论列表(0)

  1. 暂无评论