在控制器将数据发送到jsp之后,如何启动脚本

How to start a script after that the controller sends data to jsp

本文关键字:何启动 启动 脚本 之后 数据 控制器 jsp      更新时间:2023-09-26

我有index.jsp。这个jsp调用控制器:

@Controller
public class CustomerController {
    //Other code..
    //..
    String customerJSON = null;
    ModelAndView model = new ModelAndView("index", "customerJSON",  customerJSON);
    return model;
}

customerJSON是一个包含JSON信息的字符串。

Controller返回customerJSON给jsp。

现在,在jsp中,我想将customerJSON显示到一个警报中。

在jsp中添加:

<script>
    var customer = "<c:out value='${customerJSON}'/>";
    alert(customer);
</script>

问题是,这个警告在页面加载时开始,而不是在控制器返回到jsp时开始。

如何在控制器调用后显示警报,而不是在加载页面时显示警报?

我会像这样实现你的控制器方法(和requestmapping):

@RequestMapping(value = "/getCustomer")
public @ResponseBody Customer getCustomer() {
    Customer c = new Customer();
    //do whatever is needed to init customer data
    return c;
}

如果你有jackson作为依赖项,它会为你处理json序列化。

那么你的javascript(使用jquery)代码可能看起来像这样:

<script>
$.getJSON("getCustomer", data, function (result)      
{
   alert(result);
});
</script>