AJax的三种响应

AJax的响应


1.普通文本方式(字符串)
resp.getWriter().print("你好");
  //2.JSON格式当要给前台页面传输 集合或者对象时 使用普通文本传输的时String 所以要引入JSON 
后台servlet代码
    Student stu = new Student(16, "五五", 55);
          //需要导入jar包  gson-2.2.4.jar
        Gson gson = new Gson();
        String s = gson.toJson(stu);  
        //{"id":16,"name":"五五","age":55} 转换为这种格式
        System.out.println(s);
        resp.getWriter().print(s);

  

   前台代码
var text = xhr.responseText;
//传进来的
console.log(text)
console.log(typeof text) //string类型
"{"id":16,"name":"五五","age":55}"

//仍要进行转换为JSON类型 使用JSON方法
var stu= JSON.parse(text); 

console.log(stu.id)
console.log(typeof stu) //object类型
 

  


【3】XML格式(了解)

var doc= xhr.responseXML;
var name= doc.getElementsByTagName("name")[0].innerHTML;

 

猜你喜欢

转载自www.cnblogs.com/ww103/p/11985079.html
今日推荐