【问题标题】:show servlet result in textfields using jquery使用 jquery 在文本字段中显示 servlet 结果
【发布时间】:2012-04-17 22:20:50
【问题描述】:

JSP

<div id="feedback" class="statusbar"></div>

在 jQuery 中

$("#categorySave").click(function(){        
$getCode = document.getElementById("catCode").value;
$getName = document.getElementById("catName").value;
$getDesc = document.getElementById("catDesc").value;
$getDepID = $("select option:selected").val();

$(':text').val('');

$('#feedback').html('<img src="images/loading.gif"/>Processing....');

$.post("CategoryOperation", {
    catCode:$getCode,
    catName:$getName,
    catDesc:$getDesc,
    catID:$getDepID
}, function(html) {
    $("#feedback").html(html);         
});
});

在 Servlet 中(CategoryOperation)

out.println("<div>Record Inserted!</div>");

当我按下保存按钮 (id=categorySave) 时,它会在插入记录时在 div (id=feedback) 中显示消息。上面的代码工作正常。但我现在想要一点改变,那就是 成功插入记录后,它会在文本字段而不是 div 上显示结果(id=feedback)。

假设,CategoryOperation(Servlet)处理后打印如下两个,

out.println("Record Inserted!");
out.println("1");

现在我想分别在文本字段中显示以上两个输出,它们有 关注ID

id="Result"
id="Key"

如何在上面的 jquery 代码 sn-p 中通过编写以下代码或任何其他简单方法来做到这一点

$('#Result').val();
$('#Key').val();

【问题讨论】:

    标签: java javascript jquery jsp servlets


    【解决方案1】:

    您需要让 servlet 返回可解析的对象格式而不是纯文本,例如 JSON 或 XML。 jQuery 对两者都有内置支持。

    这是一个 JSON 示例:

    String json = String.format("{\"result\": \"%s\", \"key\": \"%s\"}", "Record Inserted!", "1");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
    

    Google Gson 可能会使 JSON 格式化更容易)

    需要进行如下处理:

    function(data) {
        $("#Result").val(data.result);
        $("#Key").val(data.key);
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多