我对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来实现这一点。这里有一个简单的例子:
HTML
只是一个简单的链接,就像你在问题中所做的那样。然而,我将对结构进行一点修改,使其更干净:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
这里我假设这段代码是一个带内插变量的双引号字符串。
JavaScript
既然你标记了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
看起来你知道你在这里做什么。重要的是输出适当的数据类型。
<?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);
});