【问题标题】:Using AJAX to popolate a tab with JSON使用 AJAX 使用 JSON 填充选项卡
【发布时间】:2016-12-10 08:41:33
【问题描述】:

我想修改这个 ajax 请求,使其使用接收的 JSON 填充选项卡(动态)。现在,ajax 代码只打印由 Servlet 接收的对象 json。这是jquery中的代码:

 <script type="text/javascript">

 var form = $('#form1');

 form.submit(function () {
//event.preventDefault();
  $.ajax({
  type: form.attr('method'),
  url: form.attr('action'),
  data: form.serialize(),
 success: function (data) {
 var result=data;

  $('#result').html(result);
  // Result is a ID of a <div><div> in which I  
   //  print the json string. I want build a  
   // table here. But I want that this table is dinamic,   
   // that is also the NAME of columns must depends from json                                                             
  console.log(result);
     }
  });
  return false;
});  </script>

相反,这是我的 servlet

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        HttpSession session = request.getSession();

        String k = request.getParameter("choose"); 

        //From a dropdown select, for example I choose to print
        // the table "products"
         if(k.equals("products")){  
        ArrayList<Products> list = new ArrayList<Products>();
         list =  bDBean.listProducs();

         Iterator<Products> i = list.iterator();
                while(i.hasNext()){
                Products temp = i.next();
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                String json = gson.toJson(temp);
               // response.setContentType("application/json");
                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
                }
            }
          }

【问题讨论】:

  • 你现在返回多个 json 字符串,为什么?
  • 它们是我要放置在表格中的对象
  • 响应如何??
  • 每个对象都有这种形式 = {"productNo":1, "name":"Cheese","price":5.99}...等...

标签: javascript jquery json ajax servlets


【解决方案1】:

首先将您的 javascript 代码包装在文档就绪语句中

    <script type="text/javascript">

      $(function() {
        var form = $('#form1');

        form.submit(function() {
          //event.preventDefault();
          $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: form.serialize(),
            success: function(data) {
              var table = '<table><thead><tr><td>productNo</td><td>name</td><td>price</td></tr></thead><tbody>'
              $.each(JSON.parse("["+data.split('}{').join('},{')+"]"), function(i, v) {
                table += '<tr><td>' + v.productNo + '</td><td>' + v.name +' < /td><td>'+v.price+'</td > < /tr>';
              });
              table += '</tbody></table>'
              $('#result').html(table);
            }
          });
          return false;
        });
      });

    </script>

使用下面的成功函数来显示你的表格

success: function (data) {
var table = '<table><thead><tr><td>productNo</td><td>name</td><td>price</td></tr></thead><tbody>'
$.each(JSON.parse("["+data.split('}{').join('},{')+"]"),function(i,v){
      table+= '<tr><td>'+v.productNo+'</td><td>'+v.name+'</td><td>'+v.price+'</td></tr>';
});
table+='</tbody></table>'
$('#result').html(table);
}

【讨论】:

  • 它不起作用。它刷新了将我发送到 servlet 页面的页面。它打印 {"productNo":1, "name":"Cheese","price":5.99}...等。调试发现没有进入成功:function(data)
  • 同样的问题。它没有改变任何东西
  • 你能说得更清楚点吗?对不起,但它是一个新手:/。无论如何,脚本似乎从未被激活
  • 您的 javascript 代码需要在页面加载后运行,这就是您需要文档就绪声明的原因
  • 它不起作用。无论如何,变量“形式”是没有颜色的。在 Netbeans 中通常是紫罗兰色。很郁闷..:(
【解决方案2】:

未捕获的 TypeError 可能是因为您没有解析 json 赞$.each(JSON.parse(myData), ...);

【讨论】:

  • 我是这样解决的 $.each(JSON.parse(data), function(i, v) { .... 但是表格不打印
  • 我收到这个:Uncaught SyntaxError: Unexpected token { in JSON
  • 在您尝试 JSON.parse 之前数据变量是什么样的?
  • 像这样的对象 {"productNo":1,"name":"cheese","price":9.99}
  • 也许你的数据已经是对象并且不需要解析,只需在 console.log 中尝试一件事 data[0] 看看你得到了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多