简体   繁体   中英

For Loop generate URL didn't work

I want to write {{ url('character/c1') }} to be localhost:8000/character/c1 but it didn't work inside JavaScript function.

It resulting the exact localhost:8000/{{ url('character/c1') }} link instead.

Here's my code:

<script type="text/javascript">

    var characters = [
      "geer",
      "daar",
      "geet",
      "geen"
    ]

    var character = "";
    var i;

    for (i = 0; i < characters.length; i++) {
      character += "<a href=\"\{\{ url('character/c" + i + "') \}\}\"><li></li>" + "</a>";
    }

    document.getElementById('characters').innerHTML = character;
</script>

<ul id="characters"></ul>

Add this line before the for loop

var url = window.location; // To get current window url
var url = "<?php echo $_SERVER['SERVER_NAME'] ?>" + ":<?php echo $_SERVER['SERVER_PORT'] ?>"; // To get your server name with Port

Then inside the for loop modify the line like this.

character += "<a href=\"\{\{" +  url + "('character/c" + i + "') \}\}\"><li><img src=\"character/list/c" + i +  "/icon.png\"></li>" + "</a>";

window.location will give you current url. Ofcourse, if you want your server name only. You can take the php option.

Cheers. Happy coding.

Write your for loop as this,

var url = {{ url('character') }};
for (i = 0; i < characters.length; i++) {
  character += '<a href="' + url + '/c' + i + '"><li></li></a>';
}

Thank you everyone, I have figure it out myself. It's because c1 is inside a route get(/character/{id})

for (i = 0; i < characters.length; i++) {
  character += '<a href="c' + i + '"><li></li></a>';
}

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