2011-05-15 90 views
1

我需要任何jQuery代碼來發送表單數據而無需刷新頁面。使用jquery POST POST表單

方法(POST):提交表單顯示「loading ...」消息或「加載圖像」後。如果process.php = 1(true)隱藏窗體並顯示ok消息,並且如果process.php = 2(false)不隱藏窗體並顯示任何錯誤消息。

回答

3
var data = new Object(); 
data['formData'] = $('#form').serializeArray();  
$.ajax({ 
     type: 'post', 
     url: 'process.php', 
     dataType: 'json', 
     success: function(response) { 
      if (response.result == 1) { 
       $('#form').hide(); 
      } else { 
       alert('error'); 
      } 
     } 
    }); 

process.php:

//... 
echo json_encode(array('result' => 0)); // OR 1 
+0

不錯,沒有json數據類型的方法?這不顯示ajax加載消息。 – Persipam 2011-05-15 09:21:34

+0

@persipam,我不明白你的評論)你能解釋一下嗎? – pltvs 2011-05-15 09:23:37

+0

在您的代碼提交後不顯示任何加載消息或加載圖像。 2-爲錯誤jquery顯示警報框。請看我的問題。謝謝 – Persipam 2011-05-15 09:44:53

1

您需要添加表格ID或其他識別器。

所以,如果您的形式是

<div id="message"> </div> 
<form method="post" action="" id="myForm"> 
<input type="submit" name="send" id="sendData" /> 
</form> 

的jQuery:

$(document).ready(function() { 
$("#sendData").click(function() { 
    $("#message").html("loading ..."); 
    $.post("process.php", { 
     submit: 1 //and any other POST data you separate with comma 
    }, function(response) { 
     if(response == 1) { 
      $("#myForm").hide(); 
      $("#message").html("OK"); 
     } else { 
      $("#message").html("error message"); 
     } 
    }); 
}); 
}); 

現在,經過提交表單你會得到消息 「載入中...」,同時發佈 「process.php」,然後如果process.php返回1,表單將被隱藏並顯示OK,否則您會收到錯誤消息。

+0

不錯。我測試了這個。感謝karo96。這與jQuery 1.4.4工作? – Persipam 2011-05-15 09:58:07

+0

是的,可能是,但使用最新版本的jQuery(推薦,不是$ .post)。 – 2011-05-15 10:01:02

+0

在你的代碼中沒有序列化數據! – Persipam 2011-05-15 10:05:17