关于javascript中function eval()执行后变成一个新的funciton对象的发现

Controller部分

@SuppressWarnings("unchecked")

@RequestMapping(value = "/upload", method = RequestMethod.POST)

@ResponseBody

public AjaxResult uploadFile(HttpServletRequest request, HttpServletResponse response) {

  AjaxResult result = new AjaxResult();

  String fileId = request.getParameter("fileid");

  String version = request.getParameter("version");

  String keyword = request.getParameter("keyword");

  String callback = request.getParameter("callback");

  

  ......//文件上传业务处理...

  result.setData("查询数据库返回的信息");

  request.setAttribute("callback",callback);

  request.getRequestDispatcher("/WEB-INF/jsp/file/upload_result_rp.jsp").forward(request, response);

  return result;

}

在fileList.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>File List</title>

<!-- Some contents -->

</head>

<body>

<!-- Some contents -->

<script type="text/javascript">

function callbackparam(data) {

alert(data);

}

</script>

<!-- Some contents -->

</body>

</html>

upload_result_rp.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Operate Result Callback</title>

<jsp:include page="/WEB-INF/jsp/file/fileList.jsp"></jsp:include>

</head>

<body>

<script type="text/javascript">

var result = '${result}';

if('${callback' != ""}) {

var op = window.parent?'parent':'opener';

var callback = eval('window.'+op+'.'+'{$callback}');

callback(result);

}

</script>

</body>

</html>

由于@ResponseBody,局部刷新。upload_result_rp.jsp与fileList.jsp实际上还是同一个html,相当于前者是后者的一个局部,所以前者能够调到后者中的function.

以上是一些必要的说明,接下来要表达的是eval()函数在此处的一个亮点,我以前不知道,eval()计算字符串之后可以成为一个函数对象。如果在request中,callback变量的值为callbackparam,然而在跑完var callback = eval('window.'+op+'.${callback}'); 后,实际上在此场景中var callback的callback就变成了 function callbackparam(),转而去调用fileList.jsp中的 

function callbackparam(data){

    alert(data);

}了,突然发现javascript真的很强大,有木有!!!



你可能感兴趣的:(关于javascript中function eval()执行后变成一个新的funciton对象的发现)