简体   繁体   English

对于循环生成URL无效

[英]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. 我想将{{ url('character/c1') }}localhost:8000/character/c1但是在JavaScript函数中不起作用。

It resulting the exact localhost:8000/{{ url('character/c1') }} link instead. 结果是确切的localhost:8000/{{ url('character/c1') }}链接。

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 在for循环之前添加此行

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. 然后在for循环中像这样修改行。

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. window.location将为您提供当前网址。 Ofcourse, if you want your server name only. 当然,如果只需要服务器名称。 You can take the php option. 您可以使用php选项。

Cheers. 干杯。 Happy coding. 快乐的编码。

Write your for loop as this, 这样编写您的for循环,

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}) 这是因为c1在路由get(/character/{id})

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

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

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