Spring MVC控制器返回HTML代码, JavaScript打印HTML代码

描述

比如支付宝的支付接口调用的动态生成的跳转页面,后台需要返回给前端打印跳转支付
<form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=YKCABH9dIsx0IV3QxtP5Eewm0LMe2HlNJyWotChGswakupJyuTmirTf4MH%2FtFmNOUs73swjJZUrVNhtBDFGeaxdUbAl9FT6iIvHV512NTmRQCiBrC1I9fNQ8v1YV11NNZKkIJtU7QWvi03CVKi%2B927Kzlc1gpleX9abzj51OL1JjXL7kcaM2GnIDZ6b3P3C2aOROewbDP2WuJUI7LOKh3u0MWF6um%2BKydKTrcdFl57S0fpVyREaxZYWmNRKo7TZEOxMEeNoF7Hf2%2Fr2dm7Sav%2Fq7YcdsG%2BNEKufJ1H4pZsAv2y7M1R4krN3egMm%2FFiPRG9SE3yXivpr2Ljv7sFMSzg%3D%3D&return_url=http%3A%2F%2F127.0.0.1%3A8080%2Falipay.trade.page.pay-JAVA-UTF-8%2Freturn_url.jsp¬ify_url=http%3A%2F%2F170d491b26.iok.la%2Falipay.trade.page.pay-JAVA-UTF-8%2FPayServlet&version=1.0&app_id=2016091900549628&sign_type=RSA2×tamp=2018-11-27+16%3A02%3A16&alipay_sdk=alipay-sdk-java-dynamicVersionNo&format=json">
<input type="hidden" name="biz_content" value="{"out_trade_no":"2018112716213512","total_amount":"0.01","subject":"测试","body":"第三方","product_code":"FAST_INSTANT_TRADE_PAY"}">
<input type="submit" value="立即支付" style="display:none" >
form>
<script>document.forms[0].submit();script>

这段代码是动态生成的,一旦打印成HTML加载马上submit提交跳转。
而这也是后台生成的,需要返回前端打印。而且不使用jsp,没有out.println(result)的快捷。

方法

后台

/**
 * 网页跳转支付
 *
 * @param transaction
 */
@RequestMapping(value = "/payTrade", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
@ResponseBody  //必须写
public String pagePay(Transaction transaction, HttpServletResponse response) throws AlipayApiException, IOException {
    String result = alipayService.alipayTradePagePay(transaction);
//  log.info(result);
    return result;
}

result是存储了刚刚的动态HTML代码的String变量。
能返回HTML的关键是

  1. @RequestMapper的produces = “text/html; charset=UTF-8”
  2. @ResponseBody

前端

   $.post({
        url: "xxx",
        data:xxx,
        dataType: "html",
        success: function (data) {
            console.log("成功data: " + data);
            /*
             创建新窗口对象
            var w = window.open('about:blank');
             异步写入资源
            w.document.write(data);
            w.document.close();
            w.print();
            */
     
            // 千古一句
            document.write(data);
        },
        error: function () {
            alert("异常-错误");
        }
    });

获取到的数据格式声明为 dataType: “html”
打印这个获取到的HTML代码数据的方法有两个

  1. 以新建弹窗的形式异步写入(但是一般会被浏览器拦截)
    var w = window.open(‘about:blank’);
    w.document.write(data);
    w.document.close();
    w.print();
  2. 直接 document.write(data) , 在本页面跳转

你可能感兴趣的:(前端开发,SSM,框架开发,Spring,MVC)