运行PHP脚本而不重定向或刷新页面

时间:2013-08-21 06:07:41

标签: php jquery

我是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 --------
?>

提前致谢。

2 个答案:

答案 0 :(得分:2)

您需要使用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请求。当服务器发回数据时,将触发成功功能。 Read more about .ajax() in the jQuery documentation.

如您所见,我正在使用.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();
}

答案 1 :(得分:0)

而不是<a href>,使用ajax将值传递给您的php并获得结果 -

$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
  function(data) {
    alert(data);
});
相关问题