52,797
社区成员
发帖
与我相关
我的任务
分享
$.ajax({
'url': '../Json',
'data': carAsJson,
'type': 'POST'
});
$(document).ready(function(){
var $doJSON = function doJSON(){
var car = $getCarObject();
var carAsJson = JSON.stringify(car);
$.ajax({
'url': '../Json',
'data': carAsJson,
'dataType': 'JSON',
'type': 'POST',
'success': function(data){
alert('a');
}
});
}
var $getCarObject = function getCarObject(){
return new Car("Dodge","Coronet R/T",1968,"yellow");
}
function Car(make,model,year,color){
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
$("button").click(function(){
$doJSON();
});
});
public class Json extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String json = getData(request);
try
{
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject.getInt("year") + "-" + jsonObject.getString("make") + " " + jsonObject.getString("model") + "-" + jsonObject.getString("color"));
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getData(HttpServletRequest request)
{
String line = null;
StringBuffer sb = new StringBuffer();
try
{
BufferedReader br = request.getReader();
while((line = br.readLine()) != null)
{
sb.append(line);
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
}