(1)设置自动扫描
在app-context.xml中添加
<!-- 注解扫描 -->
<context:component-scan base-package="sample"/>
只有这样才会扫描ajax处理类,才能交给spring来管理
app-context.xml是为方便用户而提供的默认配置文件,其本身被context.xml文件Import:
<import resource="app-context.xml" />
并且context.xml文件默认会被Spring自动扫描。
注意:有时候会报错,那么就不适用注解,直接使用xml形式来交给spring管理即可
(2)编写服务器端ajax处理方法
接受一个字符串,并将字符全部转换为大写,然后原字符串和处理后字符串一起返回
package sample.ajax;
import org.springframework.stereotype.Component;
import com.bstek.dorado.annotation.Expose;
@Component
public class SimpleAjax {
@Expose
public String toUpperCase(String str){
return "input:\n"+str+"\n\n"+"output:\n"+str.toUpperCase();
}
}
(3)编写前端页面,发送ajax请求
1)在页面中添加AjaxAction
设置如下值
属性
|
值
|
描述
|
---|---|---|
id |
simpleAjax | action的id |
parameter |
Hello World! | AjaxAction调用服务器端toUpperCase时的传入参数 |
service |
simpleAjax#toUpperCase | 服务定位表达式,即对应的Ajax服务 |
2)在页面中添加Button
设置button属性
属性 |
值 |
描述 |
---|---|---|
action |
simpleAjax |
单击按钮时执行的动作 |
caption | send ajax | 按钮的标题 |
3)为AjaxAction添加onSuccess事件的监听
为了能够在ajax返回的时候可以获得返回值
所以创建SimpleAjax.js
内容如下:
// @Bind #simpleAjax.onSuccess
!function(self){
dorado.MessageBox.alert(self.get("returnValue"));
}
(4)测试运行
注意:此处不是监听button的onClick事件,而是设置button的action为AjaxAction
但是更常见的,我们会使用onClick事件来监听,所以就有如下写法:
(4)常用发送ajax请求
1)定义乘法
package sample.ajax;
import org.springframework.stereotype.Component;
import com.bstek.dorado.annotation.Expose;
@Component
public class SimpleAjax {
@Expose
public String toUpperCase(String str){
return "input:\n"+str+"\n\n"+"output:\n"+str.toUpperCase();
}
@Expose
public int multiply(int num1, int num2) {
return num1 * num2;
}
}
2)定义ajaxAction
3)定义2个TextEditor
用来传递参数
4)定义button
5)定义NormalAjax.js
用来监听button的onClick事件
// @Bind #mutiply.onClick
!function(){
// 获取AjaxAction对象
var action = view.get("#normalAjax");
// 获取输入的值
var value1 = view.get("#editor1.value");
var value2 = view.get("#editor2.value");
// 将参数拼装成JSON形式
var parameter = {
num1: value1,
num2: value2
};
// 调用AjaxAction
action.set("parameter", parameter).execute(function(result){
dorado.MessageBox.alert(value1 + " * " + value2 + " = " + result);
});
}