1. 程式人生 > >MVC Ajax複雜物件封裝

MVC Ajax複雜物件封裝

objectSerializer

var objectSerializer = (function () {  
    var objectSniffer = {};  
    objectSniffer.isArray = Function.isArray || function (o) {  
        return typeof o === "object" &&  
                Object.prototype.toString.call(o) === "[object Array]";  
    };  
  
    objectSniffer.convertArrayToObject = function (arrName, array, saveOjb) {  
        var obj = saveOjb || {};  
        function func(name, arr) {  
            for (var i in arr) {  
                if (!objectSniffer.isArray(arr[i]) && typeof arr[i] === "object") {  
                    for (var j in arr[i]) {  
                        if (objectSniffer.isArray(arr[i][j])) {  
                            func(name + "[" + i + "]." + j, arr[i][j]);  
                        } else if (typeof arr[i][j] === "object") {  
                            objectSniffer.convertObject(name + "[" + i + "]." + j + ".", arr[i][j], obj);  
                        } else {  
                            obj[name + "[" + i + "]." + j] = arr[i][j];  
                        }  
                    }  
                } else {  
                    obj[name + "[" + i + "]"] = arr[i];  
                }  
            }  
        }  
  
        func(arrName, array);  
  
        return obj;  
    };  
    
    objectSniffer.convertObject = function (objName,turnObj,saveOjb) {  
        var obj = saveOjb || {};  
  
        function func(name, tobj) {  
            for (var i in tobj) {  
                if (objectSniffer.isArray(tobj[i])) {  
                    objectSniffer.convertArrayToObject(i, tobj[i], obj);  
                } else if (typeof tobj[i] === "object") {  
                    func(name + i + ".", tobj[i]);  
                } else {  
                    obj[name + i] = tobj[i];  
                }  
            }  
        }  
  
        func(objName, turnObj);  
        return obj;  
    };  
  
    return function (json, arrName) {  
        arrName = arrName || "";  
        if (typeof json !== "object") throw new Error("json引數不是json物件");  
        if (objectSniffer.isArray(json) && !arrName) throw new Error("請指定對應Action中陣列引數名稱");  
  
        if (objectSniffer.isArray(json)) {  
            return objectSniffer.convertArrayToObject(arrName, json);  
        }
        return objectSniffer.convertObject("", json);  
    };  
})();  

呼叫

$.ajax({
	url: "/admin/saveitem",
	type: "POST",
	data: objectSerializer(product),
	dataType: "text",
	complete: function () {
		msgBox.close();
	},
	success: function (response) {
		if (response) {
			alert(response);
		}
		else
		{
			productList.editBox.close();
			alert("儲存成功");
		}
	}
});

yuicompressor壓縮的js檔案在C:\Users\user 不知道有沒有引數可以設定?