2012-10-02 39 views
0

我目前正試圖讓我的Ajax從HTML表單發佈一些信息到PHP表單。在jQuery Ajax之後做功能嗎?

那麼,現在我已經在「ajax.comment.php」頁面上打印出不同的代碼,告訴發生了什麼。

如果它成功或不成功。

我現在想讓我的ajax,檢查打印的html是什麼。 然後處理該..如果(打印HTML ==「1」){然後做點什麼}。

我該怎麼做?

我下面的JavaScript是:

var name = document.comment.name.value; 
var email = document.comment.email.value; 
var website = document.comment.website.value; 
var message = document.comment.message.value; 
var id = document.comment.id.value; 
$.ajax({ 
     type: "POST", 
     url: "ajax.addcomment.php", 
     data: "name="+name+"&email="+email+"&website="+website+"&message="+message+"&id="+id, 
     beforeSend: function() { 
     // Action before sending data 
     }, 
     success: function(returned_html) { 
     // Action after sending data, where the returned_html var is the returned html text by the php 
     } 
    }); 
+0

是不是'returned_html'? – xdazz

回答

6

裏面你success功能,試試這個:

success: function(returned_html) { 
    var the_result = $.trim(returned_html); 
    if(the_result == '1') 
    { 
     // Do whatever you wanted here. 
    } 
    else 
    { 
     // Do something else here... 
    } 
} 
+2

只需提一下關於JavaScript的常用信息 - 您可能需要執行the_result ==='1'以確保結果是1和一個字符串 - 事實上,如果您要做一些事情與後來的the_result,它不表現如何你期望 – kmp

+3

實際上,運行'$ .trim()'將**總是**返回一個字符串。 – BenM

1

快要大功告成。在success回調中你只需要做你想做的事。

順便說一句,我已經序列化你的表單,以便你不需要單獨取值(除非你想對它們做些什麼)。

$.ajax({ 
     type: "POST", 
     url: "ajax.addcomment.php", 
     data: $('#comment').serialize(), 
     success: function(returned_html) { 
     if(returned_html == 1){ 
      //lets do our thing 
     } else { 
      //lets do other things 
     } 
    }); 
+0

ajax調用或任何http post/get就不會返回整數;)請在您的正確格式前3分鐘查看答案。儘管如此,仍然需要調用serialize()。 – Archer

+0

這不是身份檢查!應該工作:s。但是,修剪可能會更好。 – HungryCoder

+0

對不起 - 我的不好,我誤解了。需要測試我的眼睛:) – Archer