marți, 27 ianuarie 2015

[OmniFaces utilities (2.0)] Add the given data argument/arguments/mapping of data arguments to the current ajax response


[OmniFaces utilities] The data() methods add the given data argument/arguments/mapping of data arguments to the current ajax response.

Method (add argument):
Method (add arguments):
Method (add mapping of data arguments):
Usage of all three:

JSF Page: 
...
<h:head>
 <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script type="text/javascript">
  function showData() {
   var data = OmniFaces.Ajax.data;
   var $showData = $("#showData");

   $.each(data, function (key, value) {
     $("&lt;li&gt;").text(key + "=" + JSON.stringify(value)).appendTo($showData);
   });
  }
 </script>
</h:head>
<h:body>
 <h:form>
  <ul id="showData"></ul>
  <h:commandButton value="Show Players Data" onclick="$('#showData').empty()"
                   action="#{playersBean.showPlayers()}">
   <f:ajax />
  </h:commandButton>
 </h:form>
</h:body>
...

JSF Bean:
import org.omnifaces.util.Ajax;
...
@Named
@ViewScoped
public class PlayersBean implements Serializable {

 private List<Players> players = new ArrayList<>();
 final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

 public PlayersBean() {
  try {
      players.add(new Players(2, "NOVAK DJOKOVIC", (byte) 26, "Belgrade, Serbia",
      "Monte Carlo, Monaco", (short) 188, (byte) 80, "Boris Becker, Marian Vajda",
      sdf.parse("22.05.1987")));
      players.add(new Players(1, "RAFAEL NADAL", (byte) 27, "Manacor, Mallorca,
      Spain", "Manacor, Mallorca, Spain", (short) 185, (byte) 85, "Toni Nadal",
      sdf.parse("03.06.1986")));
      players.add(new Players(7, "TOMAS BERDYCH", (byte) 28, "Valasske Mezirici,
      Czech", "Monte Carlo, Monaco", (short) 196, (byte) 91, "Tomas Krupa",
      sdf.parse("17.09.1985")));
  } catch (ParseException ex) {
    Logger.getLogger(PlayersBean.class.getName()).log(Level.SEVERE, null, ex);
  }
 }

 public void showPlayers() {
  Ajax.data("First Player: ", players.get(0).getPlayer());
  Ajax.data("First Player:", players.get(0).getPlayer(),
            "Last Player", players.get(players.size() - 1).getPlayer());
  Map<String, Object> data = new HashMap<>();
  data.put("name", players.get(0).getPlayer());
  data.put("age", players.get(0).getAge());
  data.put("born", players.get(0).getBorn());
  data.put("heights", new Short[]{players.get(0).getHeight(),
    players.get(1).getHeight(), players.get(2).getHeight()});
  data.put("list", players);
  Ajax.data(data);
  Ajax.oncomplete("showData()");
  }

}

Output:

Niciun comentariu:

Trimiteți un comentariu