Java 在控制器向jsp发送数据之后如何启动脚本

Java 在控制器向jsp发送数据之后如何启动脚本,java,javascript,jsp,spring-mvc,controller,Java,Javascript,Jsp,Spring Mvc,Controller,我有index.jsp。此jsp调用控制器: @Controller public class CustomerController { //Other code.. //.. String customerJSON = null; ModelAndView model = new ModelAndView("index", "customerJSON", customerJSON); return model; } customerJSON是一个包

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

@Controller
public class CustomerController {

    //Other code..
    //..
    String customerJSON = null;
    ModelAndView model = new ModelAndView("index", "customerJSON",  customerJSON);
    return model;
}
customerJSON是一个包含JSON信息的字符串

控制器将customerJSON返回到jsp

现在,在jsp中,我想在警报中显示customerJSON

在jsp中,我添加:

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

var客户=”;
警惕(客户);
问题是,此警报在加载页面时启动,而不是在控制器返回jsp时启动


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

我将实现您的控制器方法(和请求映射),如下所示:

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

    return c;
}
<script>
$.getJSON("getCustomer", data, function (result)      
{
   alert(result);
});
</script>
如果您有jackson作为依赖项,它将为您处理json序列化

然后,您的javascript(使用jquery)代码可能如下所示:

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

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

$.getJSON(“getCustomer”、数据、函数(结果)
{
警报(结果);
});

您是否可以更明确地说,javascript只有在客户端(浏览器)加载后才会运行,但当浏览器甚至没有收到响应时,您的值将在服务器端的jsp中写入