在 jQuery 中用 Ajax 提交表單,有 get 與 post 兩條路。其中 get 方式搭配表單序列化格外省事——一行 $(表單ID).serialize() 就搞定了。以下把兩種方式都走一遍。
get() 透過遠端 HTTP GET 請求載入資訊,語法:
$(selector).get(url, data, success(response, status, xhr), dataType)
送兩個參數、忽略回傳:
$.get("test.php", { name: "John", time: "2pm" });
顯示回傳值:
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
serialize() 會把表單元素整理成標準的查詢字串格式。它可以直接操作被選取的表單元素(<input>、<textarea>、<select>),但實務上直接選 <form> 標籤本身通常更省事:
<form>
<div><input type="text" name="a" value="1" id="a" /></div>
<div><input type="text" name="b" value="2" id="b" /></div>
<div><input type="hidden" name="c" value="3" id="c" /></div>
<div><textarea name="d" rows="8" cols="40">4</textarea></div>
<div>
<select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
<div><input type="checkbox" name="f" value="8" id="f" /></div>
<div><input type="submit" name="g" value="Submit" id="g" /></div>
</form>
<script>
$('form').submit(function(){
alert($(this).serialize());
return false;
});
</script>
輸出會是標準查詢字串:
a=1&b=2&c=3&d=4&e=5
注意 f 沒出現——未勾選的 checkbox 不會被序列化,這點在後端接收時要留意。
jQuery.post(url, data, callback, type) 以 POST 進行非同步請求。參數說明:
· url(String):請求位址。
· data(Map,選填):以 key/value 形式表示的送出資料。
· callback(Function,選填):載入成功的回呼,只有 Response 狀態為 success 才會呼叫。
一個手機號驗證的小例子:
$.post("momsg.php", { "tel": $("#username").val() }, function(data){
// 0 成功 1 不成功 2 手機號碼格式不對
if (data == 0) { /* ... */ }
});
搭配 keyup 的即時提示:
$("input").keyup(function(){
var txt = $("input").val();
$.post("demo_ajax_gethint.asp", { suggest: txt }, function(result){
$("span").html(result);
});
});
這個例子把 ajaxStart / ajaxSend / ajaxSuccess / ajaxError 這組全域事件也一起用上,讓 Loading 與狀態訊息都有地方呈現:
<script type="text/javascript">
function adddata() {
var typeName = $("#<%=this.typeName.ClientID%>").val();
var msg = " not be empty";
if (typeName == "") {
if (msg != "") { alert(msg); return false; }
} else {
// 顯示進度條
$("#loading").ajaxStart(function(){ $(this).show(); });
// 提交前觸發
$("#msg").ajaxSend(function(request, settings){
$(this).append("<li>Starting request at " + settings.url + "</li>");
});
var countryid = $("#<%=this.drpCountry.ClientID%>").val();
var countryname = format_get_name(countryid);
var showTypeDesc = $("#<%=this.showTypeDesc.ClientID%>").val();
$.ajax({
type: "POST",
url: "addNews.aspx",
timeout: 20000,
error: function(){ alert('error'); },
data: "countryid=" + countryid + "&countryname=" + countryname
+ "&typeName=" + typeName + "&showTypeDesc=" + showTypeDesc,
success: function(msg) {
var text = msg.split('<');
$("#msg").ajaxError(function(request, settings){
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
$("#msg").ajaxSuccess(function(request, settings){
$(this).append(text[0]);
});
$("#<%=this.typeName.ClientID%>").val("");
$("#<%=this.showTypeDesc.ClientID%>").val("");
return false;
}
});
}
}
// 取得下拉選單中對應 id 的文字
function format_get_name(id) {
var drp = $('<%=drpCountry.ClientID%>');
for (var i = 0; i < drp.options.length; i++) {
if (drp.options[i].value == id) {
return drp.options[i].text;
}
}
return '';
}
</script>
最後提醒:手工拼接查詢字串時,中文與特殊字元務必經過 encodeURIComponent 處理;若表單欄位多,直接改用 $("#formId").serialize() 會安全省事得多。