2011-04-17 64 views
0

我有一個調用php頁面的ajax函數。我得到的問題是,錯誤函數不斷調用。可以讓錯誤函數調用而不是成功函數?我的ajax代碼是怎麼回事?

AJAX:

function register() { 
$.ajax({ 
    type: "POST", 
    url: "php/account.php", 
    success: function() { 
     alert("asdf"); 
    }, 
    error: function() { 
     alert("Could not register. Please try again."); 
    }, 
    404: function() { 
     alert("not found"); 
    } 
}); 
} 

PHP

<?php 
    echo "Test"; 
?> 

的文件奠定了成層次結​​構視圖看起來像這樣:

index.php 
js folder -> registration.js 
php folder -> account.php 

的registration.js和account.php是包含在index.php中,因此registration.js和account.php應該像在in中一樣在目錄中讀取dex.php。

我在做什麼錯? :X

+0

在[螢火](HTTP會發生什麼:/ /getfirebug.com/)當你發出ajax請求? – 2011-04-17 02:18:45

回答

0

使用你的代碼,但註釋掉的URL,它的工作原理:

http://jsfiddle.net/userdude/MKc3s/

function register() { 
    $.ajax({ 
     type: "POST", 
     //url: "php/account.php", 
     success: function() { 
      alert("asdf"); 
     }, 
     error: function() { 
      alert("Could not register. Please try again."); 
     }, 
     404: function() { 
      alert("not found"); 
     } 
    }); 
} 
register(); 

你應該使用Firebug在Firefox(或鉻控制檯),看看Ajax調用調用哪個網址,什麼錯誤代碼報告回來。

您還可以檢查狀態代碼返回:

function register() { 
    $.ajax({ 
     type: "POST", 
     //url: "php/account.php", 
     success: function() { 
      alert("asdf"); 
     }, 
     error: function(xhr) { 
      alert("Could not register. Please try again. Error "+xhr.status); 
     }, 
     404: function(xhr) { 
      alert("not found"); 
     } 
    }); 
} 
register(); 

在螢火/ Chrome瀏覽器的控制檯,您可以檢查整個對象:

console.log(xhr); 
+0

好吧我在Chrome中遇到了一個問題,它可能會在控制檯上如此之快,然後消失我沒有足夠的時間來看它,但我終於設法抓住它,問題出現在我的表單動作中,我修改了它到: '

' 它工作得很好,謝謝。 – 2011-04-17 02:24:32

+1

確保並檢查答案旁邊的複選標記。 :) – 2011-04-17 02:26:22

+0

@丹尼斯 - 謝謝! – 2011-04-17 02:28:30

0

檢查php/account.php(您通過ajax調用的url /函數)是否返回json,而不是html。同時檢查MIME類型是否正確。

最簡單的檢查方法:查看在firefox瀏覽器下運行的firebug的「Net」標籤。

或者使用類似etherpeek的工具,如fiddler或其他。

+0

他的示例顯示他沒有發回JSON,它不應該像現在這樣拋出錯誤,因爲文檔說它可以檢測到它是什麼:http://api.jquery.com/jQuery.ajax/。說這個電話應該指定類型。 – 2011-04-17 02:24:47