ajax提交方式詳解
在webform開發中,我們經常會用到ajax向後台提交資料,在我的公司,通常是提交到本頁的後台去處理,或者是webservice,這兩種方法都很簡便,但是總顯得略混亂。
今天在看blogengine的時候,發現它是這樣處理的
首先用一個ajaxhelper.asp教程x頁面處理全部的ajax請求,這個頁面的後台全部是:
[webmethod]
public static jsonresponse savepage(
string id,
string content,
string title,
string description,
string keywords,
string slug,
bool isfrontpage,
bool showinlist,
bool ispublished,
string parent)
{
webutils.checkrightsforadminpagespages(false);
var response = new jsonresponse { success = false };
var settings = blogsettings.instance;
if (string.isnullorempty(id) && !security.isauthorizedto(rights.createnewpages))
{
response.message = "not authorized to create new pages.";
return response;
}
….
的webmethod,這樣其實和webservice沒有本質的區別,只是比webservice更加清爽
再看看前台是如何處理的:
…
var dto = {
"id": querystring('id'),
"content": content,
"title": title,
"desc": desc,
"slug": slug,
"tags": tags,
"author": author,
"ispublished": ispublished,
"hascommentsenabled": hascommentsenabled,
"cats": cats,
"date": date,
"time": time
};
//alert(json.stringify(dto));
$.ajax({
url: "../ajaxhelper.aspx/savepost",
type: "post",
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: json.stringify(dto),
success: function (result) {
var rt = result.d;
if (rt.success) {
if (rt.data) {
window.location.href = rt.data;
} else {
showstatus("success", rt.message);
}
}
else
showstatus("warning", rt.message);
}
});
…
一個標準化的ajax提交處理機制,要比隨意的濫用好的多