【问题标题】:AJAX Usage with Servlet parameters are null带有 Servlet 参数的 AJAX 用法为空
【发布时间】:2016-06-08 07:48:24
【问题描述】:

我正在尝试从 textarea 交出文本。经过几次操作后,我想返回结果并在另一个文本区域中打印结果。

首先我的 index.jsp:第一个 textarea codeEditor 有文本。单击按钮analysisButton 后,第二个文本区域commentBox 应该会填充。

<div class="form-group">
    <label for="codeEditor" style="margin-top: 15px;">Code:</label>
    <textarea name="codeEditor" class="form-control" id="codeEditor" rows="15" style="resize: none;"></textarea>
</div>

<button id="analysisButton" class="btn btn-default btn-block" style="margin-top: 10px;">Start analysis</button>

<div class="form-group">
    <label for="comment" style="margin-top: 15px;">Comment:</label>
    <textarea class="form-control" id="commentBox" style="resize: none;height:330px;"></textarea>
</div>

然后是我的 index.js:在这里我尝试使用 AJAX,就像在这个 question 的第一个答案中一样

$('body').on('click', '#analysisButton', function(){
    $.get("AnalysisServlet",function(responseText){
        $("#commentBox").text(responseText);
    });
});

至少是我的 servlet,我称之为我的 bean

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {     
    MainVisitor mainVisitor = new MainVisitor();
    request.setAttribute("mainVisitor", mainVisitor);

    mainVisitor.setSql(request.getParameter("codeEditor"));

    String result = mainVisitor.getResult();
    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");
    resp.getWriter().write(result);
}

当我尝试在我的 MainVisitor 中设置变量 sql 时遇到 NullPointerException

编辑: 我想我的问题是我没有看codeEditor的内容

我现在将 var sql = $("#codeEditor").val(); 添加到我的 JS,但我不知道如何继续

【问题讨论】:

    标签: javascript jquery ajax jsp servlets


    【解决方案1】:

    尝试实际发送数据

    $.get("AnalysisServlet", {codeEditor: $("#codeEditor").val()}, function(responseText){
        $("#commentBox").text(responseText);
    });
    

    【讨论】:

    • 这看起来不错。我不再收到异常但值为空 --> "" empty String
    • 试试{codeEditor: 'select * from world'}作为数据参数,看看有没有收获
    【解决方案2】:

    如果您能提供完整的错误日志,那就太好了... 但我认为你的问题只是时间问题。请不要忘记 AJAX 代表 Asynchronous JavaScript and XML

    理解这一点很重要,因为在 异步 方案中,下一组命令/行已经执行,即使您仍在等待返回某些内容。您应该考虑一个回调函数。您应该放置所有您认为应该等待某个实体返回后再处理的指令。

    如果您有多余的时间,不妨阅读this

    【讨论】:

    • 这也是一件好事,谢谢。这是我的第二个问题,因为我的 textarea 也被异步填充了。
    【解决方案3】:

    你需要一个form来包裹你的textarea codeEditor。

    【讨论】:

    • 不会改变任何东西:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多