HTML (index.html):
Code: Select all
AJAX JSON Example
Code: Select all
window.onload = function()
{
var sendjsonpost = document.getElementById("sendjsonpost");
xhr = new XMLHttpRequest();
sendjsonpost.onclick = function()
{
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var country = document.getElementById("country").value;
if (name == "" || age == "" || country == "")
alert("Debe ingresar todos los datos.");
else
enviarDatosPost(name, age, country);
}
function enviarDatosPost(name, age, country)
{
xhr.onreadystatechange = prepararRespuestaPost;
xhr.open("POST", "MessagesJSON", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var datosJSON = crearDatosJSON(name, age, country);
alert(JSON.stringify(datosJSON));
xhr.send(JSON.stringify(datosJSON));
}
function crearDatosJSON(name, age, country)
{
var datosJSON = {name : name, age : age, country : country};
return datosJSON;
}
function prepararRespuestaPost()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
alert(xhr.responseText +" --- " + xhr.statusText);
}
}
}
}
Code: Select all
package com.puma.servlets;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.*;
import org.json.JSONObject;
import org.json.simple.*;
@WebServlet(asyncSupported = true, urlPatterns = { "/MessagesJSON" })
public class MessagesJSON extends HttpServlet
{
private static final long serialVersionUID = 1L;
public MessagesJSON()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
JSONObject jObj = new JSONObject(request.getParameter("name"));
Iterator iterKey = jObj.keys(); //gets all the keys
while(iterKey.hasNext())
{
String jsonKey = iterKey.next().toString();
String jsonValue = jObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
Mobile version