Ajax、Json对象及完成添加购物车的功能

前端之家收集整理的这篇文章主要介绍了Ajax、Json对象及完成添加购物车的功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Ajax:Asynchronous JavaScript and XML,其实这并不是一项新的技术,不过是融合了几种技术,实现了异步请求,即不需要刷新页面用户并不会察觉到有请求的发生,但是实际上浏览器引擎发送了请求,只不过用户不再需要等到服务器的响应才去执行其他操作。
关键对象:XMLHttpRequest
关键方法
open();发送请求
send();发送数据
属性
readyState
status (服务器返回的状态码)
responseText
responseXML
事件:onreadystatechange

function getXHR() {
     var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+,Firefox,Chrome,Opera,Safari
         xmlhttp=new XMLHttpRequest();
    } else {// code for IE6,IE5
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   return xmlhttp;
}
        //1.得到XMLHttpRequest对象
            var xhr = getXHR();
            //4.根据状态的改变执行函数
            xhr.onreadystatechange = function () {
              if(xhr.readyState == 4){
                  if(xhr.status == 200){
                       if(xhr.responseText == 'true') {
                           document.getElementById("msg").innerHTML ='用户名已存在';
                       }else if(xhr.responseText == 'false'){
                           document.getElementById("msg").innerHTML ='用户名可用';
                       }
                  }
              }
            };
            //2.open方法发起请求
            xhr.open("get","${pageContext.request.contextPath}/servlet/ajaxServlet?name="+name);
            //3.send方法
            xhr.send(null);

JSONObject对象所依赖的jar包:

package com.itdream.json;

import com.itdream.domain.Book;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/** * Created by Dream on 2017/12/7. */
public class JsonTest {
    @Test  //使用JSONObject封装数据对象类型数据
    public void test1(){
        Book b = new Book();
        b.setId("123");
        b.setName("Is your light still shinning?");
        b.setPrice(99);
        b.setCategory("启发");
        b.setPnum(15);
        b.setDescription("启发思维");

        String s = JSONObject.fromObject(b).toString();
        System.out.println(s);
    }
    //{"category":"启发","description":"启发思维","id":"123","name":"Is your light still shinning?","pnum":15,"price":99}

    @Test  //使用JSONArray封装List<Book>对象数据类型
    public void test2(){
        List<Book> list = new ArrayList<>();
        Book b1 = new Book();
        b1.setId("123");
        b1.setName("Is your light still shinning?");
        b1.setPrice(99);
        b1.setCategory("启发");
        b1.setPnum(15);
        b1.setDescription("启发思维");

        Book b2 = new Book();
        b2.setId("123");
        b2.setName("Is your light still shinning?");
        b2.setPrice(99);
        b2.setCategory("启发");
        b2.setPnum(15);
        b2.setDescription("启发思维");

        Book b3 = new Book();
        b3.setId("123");
        b3.setName("Is your light still shinning?");
        b3.setPrice(99);
        b3.setCategory("启发");
        b3.setPnum(15);
        b3.setDescription("启发思维");

        list.add(b1);
        list.add(b2);
        list.add(b3);
        String s = JSONArray.fromObject(list).toString();
        System.out.println(s);
    }
    //[{"category":"启发","price":99},{"category":"启发","price":99}]

    @Test  //使用JsonConfig去除不要的字段数据
    public void test3(){
        List<Book> list = new ArrayList<>();
        Book b1 = new Book();
        b1.setId("123");
        b1.setName("Is your light still shinning?");
        b1.setPrice(99);
        b1.setCategory("启发");
        b1.setPnum(15);
        b1.setDescription("启发思维");

        Book b2 = new Book();
        b2.setId("123");
        b2.setName("Is your light still shinning?");
        b2.setPrice(99);
        b2.setCategory("启发");
        b2.setPnum(15);
        b2.setDescription("启发思维");

        Book b3 = new Book();
        b3.setId("123");
        b3.setName("Is your light still shinning?");
        b3.setPrice(99);
        b3.setCategory("启发");
        b3.setPnum(15);
        b3.setDescription("启发思维");

        list.add(b1);
        list.add(b2);
        list.add(b3);
        JsonConfig jc = new JsonConfig();
        jc.setExcludes(new String[]{"pnum","id","category","description"});
        String s = JSONArray.fromObject(list,jc).toString();
        System.out.println(s);
    }
    //结果:
    //[{"name":"Is your light still shinning?",{"name":"Is your light still shinning?","price":99}]
}

在进行购物的时候,我们将欲购买的商品添加至购物车,购物车应该存放于session对象中
思路:
初始化的数据num=1,便于对第一次加入购物车时的数据进行数量赋值
1.首先获取session对象中的cart数据
2.如果是第一次添加购物车,那么获取的cart对象则为空,这时我们new一个购物车对象
3.判断添加的商品是否存在于购物车中,如果存在,则需要将原先存在于购物车中的商品的数量取出并进行+1操作;如果不存在于购物车中,则将初始化的num赋予给对应商品的数量
4.将商品及其num值添加到cart中
5.将cart设置到Session域中

public class AddCartServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException{
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        BookService bs = new BookService();
        Book book = bs.findBookById(id);
        Map<Book,String> cart = (Map<Book,String>) request.getSession().getAttribute("cart");
        int num = 1; //记录数量
        if(cart == null){  //第一次加购物车,购物车还没放session
            cart = new HashMap<>();
        }
        if(cart.containsKey(book)){  //如果这本书已经存在于购物车,那么则需要取出cart中的value值,+1
            String n = cart.get(book);
            num = Integer.parseInt(n)+1;
        }
        cart.put(book,num+"");
        request.getSession().setAttribute("cart",cart);
        response.getWriter().write("<a href='"+request.getContextPath()+"/servlet/pageServlet'>继续购物</a>,<a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>");
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException{
        doGet(request,response);
    }
}
原文链接:https://www.f2er.com/ajax/160549.html

猜你在找的Ajax相关文章