DWR同步调用的一点改进
DWR提供的JS方法调用默认是异步的,为了得到同步的运行结果,一般类似以下方式处理:
DWREngine.setAsync(false); //设置成同步 var _data = null; test1Ajax.sayHello('hello', function(data){_data = data;}); //dwr调用服务端的函数 DWREngine.setAsync(true); //重新设置成异步 alert(_data); //对返回值进行处理 var result = test1Ajax.sayHello('hello'); //调用同步方法 alert(result); //对返回值进行处理 test1Ajax.sayHello('hello', function(data){ alert(data);//在对返回值进行处理 });package org.directwebremoting;import java.lang.reflect.Method;import org.directwebremoting.extend.EnginePrivate;import org.directwebremoting.impl.DefaultRemoter;import org.directwebremoting.util.LocalUtil;/** * 支持DWR同步方法调用 支持DWR3.0.0.116.rc1<br> * * JS代码 异步调用:<br> * test1.sayHello("hello", function(data){ alert(data); } ); * * JS代码 同步调用:<br> * var result = test1.sayHello("hello"); <br> * alert(result); * * @author sswh * @createDate 2010-5-12 */public class SyncRemoter extends DefaultRemoter {@Overrideprotected String getMethodJS(String scriptName, Method method) {StringBuffer buffer = new StringBuffer();String methodName = method.getName();Class<?>[] paramTypes = method.getParameterTypes();// Create the sdoc commentbuffer.append("/**\n");for (int j = 0; j < paramTypes.length; j++) {if (!LocalUtil.isServletClass(paramTypes[j])) {buffer.append(" * @param {");buffer.append(paramTypes[j]);buffer.append("} p");buffer.append(j);buffer.append(" a param\n");}}buffer.append(" * @param {function|Object} callback callback function or options object\n");buffer.append(" */\n");// Create the function definitionbuffer.append(scriptName);buffer.append('.');buffer.append(methodName);buffer.append(" = function(");for (int j = 0; j < paramTypes.length; j++) {if (!LocalUtil.isServletClass(paramTypes[j])) {buffer.append("p");buffer.append(j);buffer.append(", ");}}buffer.append("callback) {\n");buffer.append(" if(callback != null){\n");// The method body calls into engine.jsbuffer.append(" return ");buffer.append(EnginePrivate.getExecuteFunctionName());buffer.append("(");buffer.append(scriptName);buffer.append("._path, '");buffer.append(scriptName);buffer.append("', '");buffer.append(methodName);buffer.append("\', arguments);\n");buffer.append(" }\n\n");buffer.append(" //synchronized\n");buffer.append(" var dwr_result = null;\n");buffer.append(" var dwr_async = dwr.engine._async;\n");buffer.append(" dwr.engine._async = false;\n");buffer.append(" var dwr_callback = function(data){dwr_result = data;};\n");buffer.append(" var dwr_arguments = [];\n");buffer.append(" for(var i=0; i<arguments.length; i++) dwr_arguments[i] = arguments[i];\n");buffer.append(" dwr_arguments[arguments.length] = dwr_callback;\n ");buffer.append(EnginePrivate.getExecuteFunctionName());buffer.append("(");buffer.append(scriptName);buffer.append("._path, '");buffer.append(scriptName);buffer.append("', '");buffer.append(methodName);buffer.append("\', dwr_arguments);\n");buffer.append(" dwr.engine._async = dwr_async;\n");buffer.append(" return dwr_result;\n");buffer.append("};\n\n");return buffer.toString();}}