詳解Sencha Touch如何向服務(wù)器提交數(shù)據(jù)
Sencha Touch如何向服務(wù)器提交數(shù)據(jù)是本文要介紹的內(nèi)容,主要是來(lái)了解Sencha Touch是如何來(lái)發(fā)送數(shù)據(jù)的。在壇子里看到一篇這樣的文章,與朋友們分享一下,具體內(nèi)容來(lái)看本文詳解。
我想要實(shí)現(xiàn)這樣的效果:讓用戶自由拖拽一些draggable的矩形控件,當(dāng)拖拽進(jìn)某個(gè)droppable區(qū)域放下時(shí),客戶端要把當(dāng)前各個(gè)droppable區(qū)域里都有哪些矩形控件了告訴服務(wù)器,服務(wù)器根據(jù)提交的數(shù)據(jù),會(huì)傳來(lái)一些新的draggable矩形控件,供繼續(xù)拖拽,所以需要向服務(wù)器提交數(shù)組形式的數(shù)據(jù),用a.jsp?id=101這種恐怕不合適,也不想用Ext.util.JSONP.request,于是打算用Ext.Ajax.request,擬把數(shù)組形式的數(shù)據(jù)轉(zhuǎn)化為json格式。
怎么辦,上代碼(參考senchtouchapi關(guān)于Ext.Ajax的內(nèi)容):
- viewplaincopytoclipboardprint?
- //提交數(shù)據(jù)
- varjData={'records':[{name:'myrecord'},{name:'anotherrecord'}]};
- Ext.Ajax.request({
- url:'http://124.16.139.80/sel_st/UpdateSympsServlet',
- //callback:function(){
- //console.log('Ext.Ajax.request');
- //},
- method:'POST',
- params:{
- records:'something'
- },
- jsonData:jData,
- success:function(response,opts){
- varobj=Ext.decode(response.responseText);
- console.dir(obj);
- },
- failure:function(response,opts){
- }
- });
- //提交數(shù)據(jù)varjData={'records':[{name:'myrecord'},{name:'anotherrecord'}]};
- Ext.Ajax.request(
- {url:'http://124.16.139.80/sel_st/UpdateSympsServlet',
- //callback:function(){//console.log('Ext.Ajax.request');//
- },
- ethod:'POST',params:{records:'something'},
- jsonData:jData,success:function(response,opts){varobj=Ext.decode(response.responseText
- );console.dir(obj);
- },failure:function(response,opts){}
- }
- );
要注意的幾個(gè)問(wèn)題:①使用了jsonData成員后,params的內(nèi)容將被忽略;
②用jsonData,那么就得method:'POST',注意全大寫,不要寫成post,Post,pOst等奇怪的樣子;
圈3callback:function()如果不注釋掉,不論成敗都會(huì)被執(zhí)行。
接下來(lái)重要的是,服務(wù)器端java代碼怎么獲取和回饋數(shù)據(jù):
如果是params:{}里面的數(shù)據(jù),用request.getParameter("id")就行了,但取jsonData:{}里面的不行,需要用request.getReader()代碼如下:
- StringBufferjb=newStringBuffer();
- Stringline=null;
- try{
- BufferedReaderreader=req.getReader();
- while((line=reader.readLine())!=null)
- jb.append(line);
- }catch(Exceptione){
- }
- System.out.println("req.getReader()"+newString(jb));
- StringBufferjb=newStringBuffer();
- Stringline=null;try{
- BufferedReaderreader=req.getReader();
- while((line=reader.readLine()
- )!=null
- )
- jb.append(line);
- }
- catch(Exceptione){}System.out.println("req.getReader()"+newString(jb));
控制臺(tái)輸出了:
- 信息:Reloadingcontext[/sel_st]
- req.getReader(){"records":[{"name":"myrecord"},{"name":"anotherrecord"}]}
嘿嘿,獲取到了。
服務(wù)器端經(jīng)過(guò)處理(暫時(shí)沒處理,返回的是無(wú)關(guān)的測(cè)試數(shù)據(jù)),返回?cái)?shù)據(jù)如下:
- [{"id":100,"sympname":"新癥狀1","belongs":"alternative"},{"id":101,"sympname":"新癥狀2","belongs":"alternative"}]
那么上面寫的varobj=Ext.decode(response.responseText);console.dir(obj);這兩行代碼會(huì)work,控制臺(tái)里輸出了:
- Array[2]
- 0:Objectbelongs:"alternative"
- id:100
- sympname:"新癥狀1"
- __proto__:Object1:Objectlength:2
- __proto__:Array[0]
嘿嘿,反饋成功,以上。
小結(jié):解析Sencha Touch向服務(wù)器提交數(shù)據(jù)的內(nèi)容介紹完了,希望通過(guò)本文的學(xué)習(xí)能對(duì)你有所幫助!