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

5

你好,我不确定这是否可能,但我想问一下 :)

我有一个包含一些信息和链接的HTML页面。链接调用JavaScript确认对话框。如果用户选择“确定”,则我想在后台调用PHP文件中的函数,即我不想改变页面、重新加载或做任何其他操作。

这可行吗?

谢谢

T

2个回答

6
使用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对象。

3
$('.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');
        }
    });

  }

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接