*在我們的代碼中,來自Ext JS頁面的參數被傳遞到Spring 3控制器,我們擁有業務邏輯。然後在控制器中,使用getWriter.write設置響應對象,並在Ext JS頁面中檢索響應。 問題:在解碼響應時,Firebug在使用Ext.util.JSON.decode時顯示錯誤,因此我們不得不使用Ext.decode來解碼來自服務器的響應。但Ext.decode提供了一個值:object Object。我需要將其轉換爲字符串或格式。 控制器代碼:將響應從服務器(JSON對象)轉換爲extjs中的字符串
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping
public class SampleController {
@RequestMapping(value = "/login.htm",method = RequestMethod.POST)
@ResponseBody
public void validateCredentials(@RequestParam("user") String user,
@RequestParam("password") String password,HttpServletResponse response) {
boolean flag = false;
String resultString = null;
try {
response.setContentType("application/json");
response.setHeader("Content-Type", "text/html, charset=utf-8");
if (user.equals(password)) {
flag = true;
resultString = "{success:true}";
} else {
flag = false;
resultString = "{success:false}";
}
response.getWriter().write(resultString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ext JS Login form :
Ext.onReady(function(){
function submit(button,event){
var uname=Ext.getCmp('user').getValue();
alert("1"+uname);
var passWord=Ext.getCmp('password').getValue();
Ext.Ajax.request({
url: 'login.htm',
method :'POST',
params: {
user:uname,
password:passWord
},
success: function(result,request) {
var jresp = Ext.JSON.decode(result.responseText);
//Ext.JSON.decode stores object Object in jresp. Our requirement is converting jresp to String or boolean
console.log('Success'+jresp);
},
failure: function(response, request) {
var jresp = Ext.JSON.decode(result.responseText);
console.log(jresp.error);
console.log('server-side failure with status code 8 ' + response.status);
}
});
}
var myform = new Ext.form.FormPanel({
title:'Login form',
frame:true,
width:400,
height: 250,
url:'login.htm',
method:'POST',
renderTo:'div1',
items:[
{
xtype:'textfield',
fieldLabel:'user',
inputType:'user',
allowBlank:false,
minLengthText:'3',
id:'user',
name:'user'
},
{
xtype:'textfield',
fieldLabel:'password',
inputType:'password',
allowBlank:false,
minLengthText:'3',
id:'password',
name:'password'
}
],
buttonAlign:'center',
buttons:[
{
text:'reset',handler:function(){myform.getForm().reset();}
},
{
text:'Login',
handler: submit
}
]
});
});
你能發表你的回覆嗎?如果是JSON,你應該可以使用JSON.Decode – sha 2012-03-23 10:58:56