繁体   English   中英

使用laravel在jQuery中使用window.location.href时未获得变量值

[英]Not getting varibles value while using window.location.href in jquery using laravel

码:

<script>
    $(document).ready(function(){
        $("#start-date-1").datepicker();
        $("#end-date-1").datepicker();
        $("#book_now").click(function(e){
            e.preventDefault();
            locations = $("#location").val();
            start_date = $("#start-date-1").val();
            end_date = $("#end-date-1").val();
            guests = $("#guests").val();
            if(locations=='' && start_date!='' && end_date!='' && guests!='')
            {
                $("#location").addClass("red_border");
            }
            else if(locations!='' && start_date!='' && end_date!='' && guests!='')
            {
                window.location.href="{{URL::to('s?location="+locations+"')}}";
            }
        });
    });
</script>

在这段代码中,我只是简单地获取locations, start_date, end_date, guestslocations, start_date, end_date, guests和所有变量值都显示在警报中,但是当我单击book_now它使用window.location.href重定向了我,但是查询字符串中的locations值为无法正确显示。

它是http://localhost/luxvacationrentalhomes.com/s?location=&quot;+locations+&quot; 它应该是http://localhost/luxvacationrentalhomes.com/s?location=2

我怎样才能解决这个问题?

   <script>
    $(document).ready(function(){
        $("#start-date-1").datepicker();
        $("#end-date-1").datepicker();
        $("#book_now").click(function(e){
            e.preventDefault();
            locations = $("#location").val();
            start_date = $("#start-date-1").val();
            end_date = $("#end-date-1").val();
            guests = $("#guests").val();
            if(locations=='' && start_date!='' && end_date!='' && guests!='')
            {
                $("#location").addClass("red_border");
            }
            else if(locations!='' && start_date!='' && end_date!='' && guests!='')
            {
                window.location.href="{{URL::to('s')}}" + "?location=" + locations;
            }
        });
    });
</script>
window.location.href="{{URL::to('s?location="+locations+"')}}";

您在这里混合了前端/后端参考框架。 {{}}内容均由后端的模板引擎处理。 您在javascript中打开" ,然后在模板引擎中将其关闭,这是行不通的。

我使用javascript字符串替换来解决类似的问题,方法是使用后端在路由上生成包含占位符的url,然后用javascript将实际值替换为前端上的url。

window.location.href="{{URL::to('s?location=ReplaceMeWithLocation')}}"
    .replace('ReplaceMeWithLocation', location);

另外,您可以使用字符串模板而不是占位符,但是原理是相同的。

window.location.href=`{{URL::to('s?location=${location}')}}`

暂无
暂无

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

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