日期:2014-05-16  浏览次数:20316 次

jquery 发送 json 格式的两个方法
这段时间,前台使用了jquery,来做一些开发,做了两个发送json格式的数据的请求,感觉有些启发。
var connect = {
      /**
     * 同步发送参数,服务器端@RequestParam,接收参数
     * @param action
     * @param method
     * @param params
     */
    sendParamSync : function (action, method, params) {
        var ret
        $.ajaxSetup({async:false});
        $.getJSON(this._basePath + action + "/" + method + ".do", params, 
         function(res, state) {
               if (state == 'success') {
                  ret = res;
               }
        })
        return ret;
    },
    /**
     * 异步发送参数,服务器端@RequestParam,接收参数
     * @param action
     * @param method
     * @param params
     */
    sendParamAsync : function (action, method, params) {
        var ret
        $.ajaxSetup({async:true});
        $.getJSON(this._basePath + action + "/" + method + ".do",params, 
        function(res, state) {
               if (state == 'success') {
                  ret = res;
               }
        })
        return ret;
    }
}


   $.ajaxSetup({async:true});

   传递的参数是一个json格式的串,$.ajaxSetup,是设置ajax的环境变量的。
  
      jQuery.extend( jQuery.ajaxSettings, settings );
   

    而 jQuery.ajaxSettings,看了一看jquery的源代码代码
   
ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		 * timeout: 0, data: null, username: null, password: null,
		 */
		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when
		// it is available
		// This function can be overriden by calling jQuery.ajaxSetup
		xhr:function(){
			return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
		},
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	}