jQuery扩展ajaxName

jQuery扩展ajaxName,用于ajax提交方法的页面数据获取,根据页面元素的name生成相应的js对象,然后可以把这个对象传给JSON编码库进行编码向后台提交,支持数组,支持.表达式

 

/*
 * jQuery Ajax By Name Plugin
 *
 * licensed under the MIT licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Author achun (achun.shx at gmail.com)
 * Create Date: 2008-6-21
 * Last Date: 2008-6-21
 * Revision:2.8.6.21
 */
(function($) {
/**
 * 获取鼠标点击的元素坐标
 */	
$.fn.clickPos = function(e){
  var pos ={x:0,y:0};
  if (e.offsetX != undefined) {
    pos.x = e.offsetX;
    pos.y = e.offsetY;
  } else if (typeof $.fn.offset == 'function') {
    var offset = this.offset();
    pos.x = e.pageX - offset.left;
    pos.y = e.pageY - offset.top;
  } else {
    pos.x = e.pageX - this[0].offsetLeft;
    pos.y = e.pageY - this[0].offsetTop;
  }	
  return pos;
}
/**
 * ajaxName() 根据标签name属性来提交数据,替代form提交方式
 * options:{//与ajax的options是一样的结构
 *	data:{}//要附加提交的数据
 * }
 * successful:如果元素有有效值,defualt:true
 */
$.fn.ajaxName = function(options,successful) {
	if(options==undefined) options={};
	options.data = options.data || {};
  successful = successful == undefined ? true:successful;
	var data = {};
	var name= options.name || '';
	this.each(function() {
  	var el=this,o=$(this),n = o.attr('name'),hasval = o.attr('value')!=undefined;
  	if (!n) return;
  	var t = el.type, tag = el.tagName.toLowerCase();
		if (n=='/'){
			if (name=='') name = hasval?o.attr('value'):o.text();
			return;
		}
    if (successful && (el.disabled || t == 'reset' || t == 'button' ||
	      (t == 'checkbox' || t == 'radio') && !el.checked ||
	      (t == 'submit' || t == 'image') ||
	      tag == 'select' && el.selectedIndex == -1))
      return;
    var v= hasval? o.attr('value') :o.hasClass('ValueByText')?o.text():o.html();
    if (v == undefined) return;
  	if (n.indexOf('.')>0){
    	n=n.split('.');
    	var len=n.length - 1;
    	var b=data;
      $.each(n,function(i){
		    if (i!=len){
		    	if(b[this] == undefined) b[this]={};
	        b=b[this];
		    }else
	        b[this]=v;
    	});
  	}else if (n.indexOf('[]')>0){
    	n=n.slice(0,n.length-2);
    	if(data[n] == undefined) data[n]=[];
    	data[n].push(v);
		}else{
			data[n]=v;
		}
  });
  var dat={};
  if (name){
  	dat[name]=data;
	  data=dat[name];
  }else
  	dat=data;
  for (var o in options.data){
  	data[o]=options.data[o];
  };
  options.data=dat;
  return options.data;
};
})(jQuery);
 

你可能感兴趣的:(jquery,json,Ajax,Gmail,OpenSource)