2017-04-04 119 views
1

我有一个PHP链接如下,出现一个模式里面:传递JavaScript变量PHP链接

<?php echo $this->Html->link('Cart', ['controller' => 'payments', 'action' => 'cart', ]); ?> 

我也有一个脚本,它提出了模态:

$('.pay').click(function (ev) { 
    ev.preventDefault(); 
    $('#payModal').modal('show'); 
    var bookingId = $(this).attr('data-id'); 
}); 

我会喜欢尝试将JavaScript变量bookingId传递给PHP链接。我想通过一个表单来做,但我没有提交任何内容,因此在发布帖子/请求时没有任何内容会显示出来。

+0

你的意思是导航到另一个页面?你可以用javascript来做到这一点:'window.location ='/yoursite.php?booking_id='+ bookingId' –

+0

我导航到的网站格式为'localhost \ site \ payments \ cart \ bookingId'。如果我将'window.location'设置为该网址,那么用户如何点击链接实际上将它们带到那个位置?我是否在单独的脚本中设置'window.location',或者在触发模式的同一脚本中设置? – mistaq

回答

0

在模式脚本,我在下面说:

$('.pay').click(function (ev) { 
    ev.preventDefault(); 
    var bookingId = $(this).attr('data-id'); 
    $('#payModal').modal('show'); 
    $('#payModal').attr('bookingId',bookingId); //added in this line, setting the bookingId variable as an attribute of the modal. 
}); 

然后我改变了我的PHP链接到一个标准的HTML按钮:

<button onclick="cartredirect()">Proceed to Cart</button> 

这随后触发第二JavaScript的:

<script> 
    function cartredirect(){ 
      var bookingId = $("#payModal").attr('bookingId'); //returns the modal attribute from before. 
      window.location = "<?= $host . $basepath ?>/payments/cart/" + bookingId; //now as a result, the page with the correctly appended variable can load. 
    }; 
</script> 
-1

**

正如你已经知道PHP和JS都是脚本语言和他们绑定 到一个变量,因为他们执行的,所以用你给的 信息的JS使用

**

$('.pay').on ('click',function (ev) { 
ev.preventDefault(); 
    $('#payModal').modal('show'); 
    var bookingId = $(this).attr('data-id'); 
}); 

如果这不起作用生成在与JS链接附加到HTML

1

我依赖如果您的HTTP请求中有其他GET参数。如果没有,您可以导航到当前路径并追加所需的GET参数。

window.location = '?booking_id=' + bookingId; //navigate to the current page 
window.location = './othersite.php?booking_id=' + bookingId; //navigate to another page 

这将导航至当前页面只用booking_id作为GET参数。

如果你想保留你的其他参数,你必须解析当前的URL,追加你的参数,然后把它序列化回一个URL并改变它的位置。

只是为了澄清有关相对链接在这里的一些事情:

//lets take the following URL as an example 
'https://www.example.com/blog/pages/2984?id=3' 

''  //current page --> 'https://www.example.com/blog/pages/2984' 
'./'  //current 'directory' you are in --> 'https://www.example.com/blog/pages' 
'../' //parent 'directory' --> 'https://www.example.com/blog' 
'../../' //2nd parent 'directory' --> 'https://www.example.com' 
'/'  //root 'directory' --> 'https://www.example.com' 
+0

虽然我试图从当前页面导航到新页面。即用户用上面的脚本打开模态,然后点击模态中的链接。该模式中的链接然后将用户重定向到新页面,该页面附加了'bookingId'变量。 – mistaq

+0

@mistaq是否适合你? –

+0

我设法让它以不同的方式工作,但将一些答案与'window.location'结合。我会尽快回复。 – mistaq