利用ajax向服务器发送json格式的数据,以及服务器端的接收和处理
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
1.首先我们需要json.js这个js文件,因为我们要利用JSON对象把对象变为JSON串,例如
var person = {
name : 'yewenjun',
school: 'zafu'
};
var json = JSON.stringify(person);//把person变为json串
然后我们用xml对象的send方法来发送转化好的JSON串
xml.send(json);
2.在服务器端接收和处理,下面是在servlet里的一个方法,它的作用是利用request接收请求的数据,并把它转化为字符串
private String readJSONStringFromRequestBody(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try{
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){//一行一行的读数据
json.append(line);
}
}catch(Exception e){
System.out.println("Error reading JSON String " + e.toString());
}
return json.toString();//变为字符串返回
}
3.把转换成的字符串变为JSON对象,并且用getString方法提取出数据,这里需要一个jar包:java-json.jar,这个包含有所有必须的文件
下载链接:https://pan.baidu.com/s/1TEGFE9XLCQ5Vb1ye7bBouQ 密码:1ggh
String person = readJSONStringFromRequestBody(request);
JSONObject jsonObject = null;
try{
jsonObject = new JSONObject(person);
}catch(Exception e){
System.out.println("get JSONObject Error: " + e.toString());
}
// out.println(jsonObject);
String responseText = "";
try {
responseText = jsonObject.getString("name") + " " + jsonObject.getString("school");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(responseText);
最后利用out.println把数据返回
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:24 天前 )
960b763e
3 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献2条内容
所有评论(0)