Javascript h ref not correctly matched

88 Views Asked by At

In my web app I have various .jspx pages, in one of this I want compose it dinamically by javascript.

I want to create a table with the data element, every data element have an index.

I compose a var, named url, with the path and the id of element:
var url = "${downloaHistodyUrl}"+data[index].id;

My problem is that the url is set correctly (I had used the alert for debug it). But, when I click on: <a href> element I have the "url" world, instead of the value of the variable and my path is: "/mypath/"+url+ .

CODE:

$('#modal_history_${doc.id}').on('show.bs.modal', function(e) {
     $.getJSON('${historyUrl}', function(data) {
        var html='<table class="table table-hover"><tr><th>Versione</th><th>Nome</th><th>PDF</th><th>Motivazione</th></tr>';
        $.each(data, function(index) {
            html = html+"<tr><td>"+data[index].versione+"</td>";
            if(data[index].fileName != null){
                var url = "${downloaHistodyUrl}"+data[index].id;
                alert(url);
                html = html+'<td>'+data[index].fileName+'</td><td><a href='+url+' ><span class="fa fa-download"> Download</span></a></td>';
            }else{
                html = html+"<td></td>";
            }
            if(data[index].motivazione == "" || data[index].motivazione == null){
                html = html+"<td></td>";
            }else{
                html = html+"<td>"+data[index].motivazione+"</td>";
            }
            html = html+'</tr>';
        });
        html = html+'</table>';
        $('#content_modal_history_${doc.id}').append(html);
     })
});

I don't understand why.. Anyone can help me?

2

There are 2 best solutions below

6
Jmartnz On

The problem is that you need to escape the slash '/' characters in your url variable. Otherwise they will have the effect you are experiencing, that is, they will make the single quotes appear in the final output.

Edit: In case you didn't understand, what I mean is changing/replacing the slashes (/) with double slashes like (//). I also recommend you to use the concat method instead of using the add (+) operator for strings, for a cleaner code.

1
krom On

You're missing the double quotes on the href attribute. You have <a href=myurl while it needs to be <a href="myurl"

Also, double-check that you really used single quotes when adding url to the string and not double quotes. If you did something like this, it would exactly cause the problem you're describing:

html = '<a href="+url+">click me</a>'

Your code should read like this:

html = html+'<td>'+data[index].fileName+'</td><td><a href="'+url+'"><span class="fa fa-download"> Download</span></a></td>';