使用 JavaScript 确认对话框在后台进行 PHP 调用


Use JavaScript confirm dialog to make a PHP call in the background

好吧,不太确定这是否可能,但我想我还是会问:)

我有一个包含一些信息和链接的HTML页面。该链接调用 JavaScript 确认对话框。如果用户选择确定,那么我想在 PHP 文件中调用一个函数,但在后台,即我不想更改页面、重新加载或任何东西。

这可能吗?

谢谢

T

使用 AJAX。 下面使用 jQuery:

if(confirm('Are you sure?')) {
    $.ajax({
        url: '/path/to/file.php',
        data: 'url=encoded&query=string', // Can also be an object
        success: function(output) {
            // This function is called after the PHP file completes.
            // The variable passed in is a string containing all output of
            // your PHP script (i.e. echo / print )
        }
    });
}

有关更多信息,请查看 jQuery 的 AJAX 文档。 如果你不能使用 jQuery,有很多关于使用原生 JavaScript 发出 AJAX 请求的教程。

如果要从 PHP 将大量数据返回到成功函数,则值得将 PHP 中的数据作为 JSON 编码数组返回,该数组可以在客户端安全地解析为 JavaScript 对象。

$('.LinkClass').click(function(){
  if( confirm('Is it OK?') ) {
    $.ajax({
        url: 'action.php',
        type: 'POST',
        data: 'data=value', // Can also be an object
        success: function(data) {
            // Do Nothing
        },
        error: function(){
           alert('Error');
        }
    });
  }
});