[英]Running a PHP Script without redirecting or refreshing the page
我是PHP和Javascript的新手。 現在我通過使用它運行PHP腳本,但它重定向到另一個頁面。 代碼是
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
如何在不重定向到另一個頁面的情況下執行此代碼並獲取成功和失敗警報消息的彈出窗口。
我的腳本代碼是 -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
提前致謝。
您需要使用AJAX來執行此操作。 這是一個簡單的例子:
只是一個簡單的鏈接,就像你在問題中一樣。 但是我會稍微修改一下結構以保持它更清潔:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
我在這里假設這段代碼是帶引號變量的雙引號字符串。
既然你標記了jQuery ......我將使用jQuery :)
瀏覽器將偵聽鏈接上的click
事件,並對相應的URL執行AJAX請求。 當服務器發回數據時,將觸發成功功能。 在jQuery文檔中閱讀有關.ajax()
更多信息。
如您所見,我使用.data()
來獲取GET參數。
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
看起來你知道你在這里做什么。 重要的是輸出適當的數據類型。
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
而不是<a href>
,使用ajax將值傳遞給您的PHP並獲得結果 -
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.