2012-08-09 34 views
2

由於某種原因,我無法得到這個工作。我想要做的就是當點擊一個按鈕時,(通過ajax)執行一個php文件。阿卡,如果我沒有使用AJAX,我們會看:基本Ajax與jQuery - 執行PHP文件

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

我想要的文件,而無需離開當前頁面被執行。

這是我有個大氣壓:

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

在上面的代碼中,如果返回的數據「記錄在」比出現一個消息框平等。否則,它會重定向到該位置(通過數據發送)。由於某些原因,這個if語句無法正常工作,但數據正按預期返回。

我的PHP代碼:

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

>

任何想法?

+1

嘗試用'on'替換'live',因爲live已被棄用! 也檢查php文件的路徑是否正確 – UnLoCo 2012-08-09 02:33:46

+0

這對我來說並不是錯誤的 - 您是試圖從PHP文件獲取響應還是隻需設置一些內容並忘記它? – 2012-08-09 02:35:10

+0

根本無法工作(也就是說,測試警報也不會觸發)。 – Andrew 2012-08-09 02:35:47

回答

5

如果你不想離開頁面,做

$(".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可以增加簡單性而不是可用性和更多選項。

+0

我對此有點困惑。數據是一個分配了php文件返回值的變量嗎? – Andrew 2012-08-09 03:04:45

+0

從測試它,是的,是這樣的。謝謝:)這將工作:) – Andrew 2012-08-09 03:06:49

+0

是的,它是。對不起,沒有真正完成閱讀快速回復;) – 2012-08-09 03:06:58