3

出于某种原因,我无法让它工作。我想要做的是,当单击按钮时,(通过 ajax)执行一个 php 文件。Aka,如果我不使用 ajax,我们会看:

<a href="file.php">dfgdfg</a>

我希望在不离开页面的情况下执行文件。

这就是我的atm:

$(".vote-up").live('click', function(e) {
$.ajax("file.php", function(){
       alert("Executed file");
   });
});

这似乎不起作用。我真的很困惑 jQuery ajax 函数一般是如何工作的,而没有处理任何远程复杂的事情。

添加的问题:

.ajax({
       url: 'includes/login-check-jquery.php',
       success: function (data) {
            if(data == 1){
                alert("Logged in!!!");
            }else{
                window.location = data;
            }
        error: function (xhr, status, error) {
        // executed if something went wrong during call
        if (xhr.status > 0) alert('Error: ' + status); // status 0 - when load is interrupted
        }
    });
});

在上面的代码中,如果返回的数据等于“logged in”,则会出现一个消息框。否则它将重定向到该位置(以数据形式发送)。由于某种原因,此 if 语句不起作用,但数据按预期返回。

我的 PHP 代码是:

<?php  
if (!$user->logged_in){
    echo "../login/index.php";
}else{
    echo "1";
}

?>

有任何想法吗?

4

1 回答 1

6

如果您不想离开页面,请执行

$(".vote-up").live('click', function(e) {
    e.preventDefault();
    ...

如果需要,可以更新 ajax

$.ajax({
    url: 'file.php',
    success: function (data) {
        // this is executed when ajax call finished well
        alert('content of the executed page: ' + data);
    },
    error: function (xhr, status, error) {
        // executed if something went wrong during call
        if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
    }
});

如果您追求简单性而不是可用性,则可以删除错误回调部分,并且可以通过引用jquery ajax doc添加更多选项。

于 2012-08-09T02:59:44.797 回答