我有一个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。我想通过一份表格来完成它,但是我没有提交任何东西,所以在做一个帖子/请求时什么都不会出现。
发布于 2017-04-03 22:35:32
在情态脚本中,我添加了以下内容:
$('.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>
发布于 2017-04-03 21:46:28
我依赖于您的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并将位置更改为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'
发布于 2017-04-03 21:46:25
**
正如您已经知道的,PHP和Js都是脚本语言,它们在执行时绑定到一个变量,所以使用您提供的用于js的信息
**
$('.pay').on ('click',function (ev) {
ev.preventDefault();
$('#payModal').modal('show');
var bookingId = $(this).attr('data-id');
});
如果这不起作用,生成您在js中的链接,并附加到html
https://stackoverflow.com/questions/43198936
复制