如何从jsp页面返回值

时间:2016-09-07 04:16:54

标签: java json jsp

我有一个jsp页面,它有java scriplets,并且使用out.println(obj)显示所需的输出,但我想返回此'obj',以便这些值可以在另一个js文件中使用。如何从jsp页面返回?

所以js文件是:

(function() {

    document.addEventListener('DOMContentLoaded', function() {

        var gridDiv = document.querySelector('#myGrid');

        var gridOptions = {
            columnDefs: [
                {headerName: 'CLIENT_ACRONYM', field: 'CLIENT_ACRONYM'},
                {headerName: 'ORDER_QTY', field: 'ORDER_QTY'},

            ]
        };

        new agGrid.Grid(gridDiv, gridOptions);

        jsonLoad( function(data) {
            gridOptions.api.setRowData(data);
        });
    });
    })();


function jsonLoad(callback) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', '../output.json'); // by default async
    xhr.responseType = 'json'; // in which format you expect the response to be

    xhr.onload = function() {
        if(this.status == 200) {// onload called even on 404 etc so check the status
            callback(this.response);
        }
    };

    xhr.onerror = function() {
        console.log('loading data error');
    };

    xhr.send();
}

返回Jsonarray的JSP文件:

JSONArray jsonArray = new JSONArray(orderDetailsList1);

response.setContentType("application/json");
       response.setCharacterEncoding("UTF-8");
       response.getWriter().write(jsonArray);

因此,我需要传递jsp文件返回的JSOn对象,而不是js文件中的output.json。怎么做?

2 个答案:

答案 0 :(得分:1)

在jsp文件中使用此代码

<input type="hidden" value="<%out.println(obj);%>" id="objValue"/>

在js文件中,您可以通过id获取值

var objValue = document.getElementById("objValue");

基本上jsp中的scriplets并不好。

存储在会话范围或请求范围内并使用它,例如servlet中的session.setAttribute('obj','value')和jsp中的value="${obj}"

答案 1 :(得分:0)

将该值放在jsp中具有ID的<div id=""><p id="">标记中,并使用getElementByID在任何js中获取该值。

相关问题