前端——方法一:eval
document.getElementById("button1").addEventListener('click', ()=> {
let xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8090/helloword", true)
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var text = xhr.response
console.log(text)
eval("var json = " + text)
console.log(json.name)
console.log(json.age)
console.log(json.sex)
}
}
}
xhr.send("zoreId=1&data=12")
})
前端——方法二:JSON.parse
document.getElementById("button1").addEventListener('click', ()=> {
let xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8090/helloword", true)
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var text = xhr.response
console.log(text)
var json = JSON.parse(text)
console.log(json.name)
console.log(json.age)
console.log(json.sex)
}
}
}
xhr.send("zoreId=1&data=12")
})
后端——使用gson转化成json格式
@RequestMapping("/helloword")
public String helloword(String zoreId, String data){
System.out.println(zoreId+ " " +data);
Student student = new Student("ly", 12, 1);
Gson gson = new Gson();
String result = gson.toJson(student);
return result;
}
前端——json对象转化为json字符串
var s = JSON.stringify(json)