用Ext 實現 JSONRPC 客戶端

json rpc 詳細協議鏈接

 

 

var JsonRpcClient = function(config) // url , method ,callback  this there parameters is mandatory
{
	//private data
	var _callbackObj = {};
	var _reqRespMapping = [];
	var _createId = function() 
	{
		return ""+(new Date()).getTime();
	};
	var _send = function(jsonData)
	{		
		var _sync=false;
		if(config.sync) _sync=config.sync;
		
		Ext.Ajax.request({
		    method:'POST',
			url: config.url,
			sync:_sync,
			success: function(res)
			{
				response = Ext.decode(res.responseText);
				_reqRespMapping.remove(response.id);				
				if(config.callback)
				{
				   config.callback(response);				
				}			

			},
			failure: function()
			{
				_reqRespMapping.remove(jsonData.id);
				if(config.callback)
				{
				   config.callback({"error":true,result:''});				
				}	
			},
			jsonData : jsonData,
			headers:{"Content-Type":"application/json-rpc;charset=UTF-8"}
		});
	};
	
	
      this[config.method]=function()
      {
		var id = _createId();
		var args = [];
		for(var i=0;i<arguments.length;i++)
		{
			args[i]=arguments[i];
		}		
		var jsonRpcReq = {
			method: config.method,
			params: args,
			id: id
		};
		_reqRespMapping[id] = jsonRpcReq;
		_send(jsonRpcReq);
	
      }
}

  在使用jsonplugin  會遇到協議頭的解析錯誤,原因是Ext.Ajax 對協議頭重複和錯誤包裝,可以複寫initHeader 方法達到協議的頭正確設置代碼如下:

  

 

Ext.lib.Ajax.initHeader=function(label, value, isDefault)
   {
            var headerObj = (isDefault) ? this.defaultHeaders : this.headers;

            if (headerObj[label] === undefined) {
                headerObj[label] = value;
            }
            else {

                headerObj[label] = headerObj[label] + "," + value;// 新協議頭的定義放到最後面
            }

            if (isDefault) {
                this.hasDefaultHeaders = true;
            }
            else {
                this.hasHeaders = true;
            }
   }

 

 js 調用也非常的簡單

var client=new JsonRpcClient({url:'xxx.action',method:'xxxmethod',sync:true,callback:function(res){});
client.xxxmethod();

 首先初始化一個 rpc  cilent  ;

 method :遠程方法名

 sync :是否同步調用

 callback : 回調函數

初始化完畢 cilent 就是調用遠程的方法了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章