blinkettaro blinkettaro - 3 months ago 8
Javascript Question

Using AJAX to popolate a tab with JSON

I want to modify this ajax request in such a way it populates a tab (dinamically) with a JSON that receives. NOW the ajax code prints only the object json that receives by a Servlet. This is the code in 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>


Instead, this is my 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);
}
}
}

Answer

First wrap your javascript code in a document ready statement

    <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>

use the following success function to display your table

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);
}
Comments