簡體   English   中英

將Javascript變量傳遞給PHP鏈接

[英]Passing Javascript variable to PHP link

我有一個如下的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鏈接。 我想通過一個表單來做,但我沒有提交任何東西,所以在做一個帖子/請求時什么都不會出現。

我依賴你的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'

在模態腳本中,我添加了以下內容:

$('.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>

**

因為您已經知道PHP和Js都是腳本語言,並且它們在執行時綁定到變量,所以使用您為js使用的信息

**

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

如果這不起作用生成你鏈接在js與追加到HTML

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM