java - 使用 Hibernate 在 ArrayList 中进行 Ajax 响应

标签 java jquery ajax hibernate arraylist

我正在开发一个项目,客户要求是...如果用户从下拉菜单中选择一种特定类型,以便数据应显示在下一个下拉菜单中,例如有 3 个列表(价格表、平板列表、区域列表)。如果用户选择价目表,则只有价目表数据应显示在下一个下拉菜单中。 我几乎到达那里,但我收到了 ArrayList 格式的 data(response) 我不知道下一步。我的意思是如何将响应数据放入下拉菜单中。

这是我的代码:

PriceListMapping.jsp

<select name="pricelisttype" id="pricelisttype" onchange="getPriceListType()">
   <option value="" >Select PriceList Type </option>
   <option value="G" >General Price List</option>
   <option value="S" >Slab Price List</option>
   <option value="Z" >Zone Price List</option>
</select>

<select name="pricinglist" id="pricinglist">
   <option value='0' >Select Price List </option>
</select>
function getPriceListType(){
  var pricelisttype = $('#pricelisttype').val();
  $.ajax({
    url: "getPriceListType",
    method: "GET",
    data: { pricelisttype: pricelisttype },
    dataType: 'text',
    success: function (data) {
      $('#pricinglist').html(data);
      $('#a').html(data);             
    }      
  });
}

PriceListMappingView.java

String pricelisttype = request.getParameter("pricelisttype");
if (pricelisttype.equalsIgnoreCase("G"))
{
  transaction.setBiginTransaction();
  List<Object[]> l = transaction.s.createQuery("select generalPricingIds from Pricelistmaster").list();
  transaction.setCommitTransaction();
  response.getWriter().print(l);
}

<强> Before onchange my output

<强> After onchange my output

最佳答案

在您的具体情况下,我建议您避免尝试使用 Javascript 过滤网页内的价目表,而是在 Controller 内影响它。

@RequestMapping("/pricelists")
public @ResponseBody getPriceLists(@RequestParam("type") String type) {
  if ( "G".equals( type ) ) {
    // ignore this type, return an empty list perhaps??
    return Collections.emptyList();
  }
  else {
    // query the database doing something like
    // SELECT * FROM PriceListTable WHERE PriceListType = :priceListType
    return priceLists.getPriceListsByType( type );
  }
}

在页面中,您需要关心的就是获取 json 数组并将其附加到您的 <select/> 中。 html 标签。

function(data) {
  var toAppend = '';
  $.each (data, function( i, o ) ) {
    toAppend = '<option value=' + o.value + '>' + o.name + '</option>';
  } );
  $( "pricingList" )
   .find("option")
   .remove()
   .end()
   .append( toAppend );
}

对于使用服务器端标记而不是依赖 Javascript 来渲染组件的逻辑可能更容易的情况,我建议您考虑使用 HTML 部分。原始页面仍然发出 AJAX 请求,但 Controller 不会返回 JSON,而是像原始页面一样转发到 View 页面。 AJAX 请求期望得到 html 的响应而不是json并且可以简单地进行 dom 元素替换。

关于java - 使用 Hibernate 在 ArrayList 中进行 Ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42717632/

相关文章:

java - 如何将 RDF 转换为字符串

javascript - 我如何在我的网站上使用 jquery?

javascript - 围绕纯 js 组件创建 asp.net ajax 控件是否比通过 jquery 执行 ajax 更好?

java - Realm :使用 beginGroup() 和 endGroup() 进行查询时出现语法错误

java - 为什么我的第二个 sqlite 表抛出异常?

javascript - Mocha 测试与焦点相关的行为(Backbone/CoffeeScript 应用程序)

javascript - jqueryui datepicker 不显示范围内的所有年份

jquery - 从 jQuery POST 中删除一些文本

javascript - 通过ajax和jquery上传文件

java - 如何在 Java 中初始化字节数组?