asp.net mvc 對ajax 支援的很好,但對於用vs2005開發的朋友,想和asp.net mvc一樣優雅的開發ajax程式,需要自己實現的東西太多。為了對傳過去項目不做大的改動,又實現ajax效果,我利用了iframe實現了ajax效果。
核心ajax代碼如下:
Code
1var frameAjaxDic = new Object();
2 var frameAjax = function(id, onStart, onComplete) {
3 this._id = id
4 if (frameAjaxDic[this._id] != true) {
5 $("body").append("<iframe style='display:none' src='about:blank' id='" + this._id + "' name='" + this._id + "'></iframe>");
6 frameAjaxDic[this._id] = true;
7 }
8 this.onStart = onStart;
9 this.onComplete = onComplete;
10 this.isFormPost = false;
11 }
12 frameAjax.prototype = {
13 getId: function() {
14 return this._id;
15 },
16 submit: function(form) {
17 if (!this.isFormPost) {
18 $(form).attr("target", this._id);
19 var self = this;
20 if (this.onStart != null) {
21 this.isFormPost = this.onStart();
22 if (this.isFormPost) {
23 $("#" + this._id).load(function() { self._onframeload(); });
24 }
25 }
26 }
27 return this.isFormPost;
28 },
29 _onframeload: function() {
30 if (this.isFormPost) {
31 this.isFormPost = false;
32 if (this.onComplete != null) {
33 this.onComplete($("#" + this._id).contents().text());
34 }
35 $("#" + this._id).unbind("load");
36 }
37 },
38 despose: function() {
39 this.onStart = null;
40 this.onComplete = null;
41 $("#" + this._id).remove();
42 frameAjaxDic[this._id] = null;
43 }
44 }
這個javascript對象的意圖是建立個iframe,把向本頁面提交的操作轉到向iframe提交,從而實現提交頁面的不重新整理,並將伺服器端執行結果返回iframe.
下面是這段代碼的三個應用:1、上傳 2、添加單個對象 3、添加多個對象。
iframeAjax應用例子