前台可以获取到数据,但通过ajax传到后台就没有了

前台可以获取到数据,但通过ajax传到后台就没有了

http://img1.sycdn.imooc.com//climg/5f48cfdb09cbf1a600000000.jpg

http://img1.sycdn.imooc.com//climg/5f48d0b109da57ce08120224.jpg

http://img1.sycdn.imooc.com//climg/5f48cfdb09bc61a019221032.jpg

$(function () {
    var initUrl = '/o2o/shop/info_init';
    var registerUrl = '/o2o/shop/register';
    getInitInfo();
    function getInitInfo() {
        $.getJSON(initUrl, function (data) {
            if (data.success) {
                var tempHtml = '';
                var tempAreaHtml = '';
                data.shopCategoryList.map(function (item) {
                    tempHtml += '<option data-id="' + item.shopCategoryId + '">'
                        + item.shopCategoryName + '</option>';
                })
                data.areaList.map(function (item) {
                    tempAreaHtml += '<option data-id="' + item.areaId + '">'
                        + item.areaName + '</option>';
                })
                $('#shop-category').html(tempHtml);
                $('#area').html(tempAreaHtml);
            }
        });
    }

    $('#submit').click(function () {
        var shop = {};
        shop.shopName = $('#shop-name').val();
        shop.shopAddr = $('#shop-addr').val();
        shop.phone = $('#shop-phone').val();
        shop.shopDesc = $('#shop-desc').val();
        shop.shopCategory = {
            shopCategoryId: $('#shop-category').find('option').not(function () {
                return !this.selected;
            }).data('id')
        };
        shop.area = {
            areaId: $('#area').find('option').not(function () {
                return !this.selected;
            }).data('id')
        };
        var shopImg = $('#shop-img')[0].files[0];
        var formData = new FormData();
        // 添加图片流进表单对象里
        formData.append('shopImg', shopImg);
        // 将shop json对象转成字符流保存至表单对象key为shopStr的的键值对里
        formData.append('shopStr', JSON.stringify(shop));
        // 获取表单里输入的验证码
        var verifyCodeActual = $('#verify-code').val();
        if (!verifyCodeActual) {
            $.toast('请输入验证码');
            return;
        }
        formData.append('verifyCodeActual', verifyCodeActual);
        // 将数据提交至后台处理相关操作
        $.ajax({
            url : registerUrl,
            type : 'POST',
            data : formData,
            contentType : false,
            processData : false,
            cache : false,
            success : function(data) {
                if (data.success) {
                    $.toast('提交成功!');
                } else {
                    $.toast('提交失败!' + data.errMsg);
                }
                // 点击验证码图片的时候,注册码会改变
                $('#kaptcha_img').click();
            }
        });
    });
})
package com.imooc.o2o.web.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.PersonInfo;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.AreaService;
import com.imooc.o2o.service.ShopCategoryService;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.CodeUtil;
import com.imooc.o2o.util.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("shop")
public class ShopManagementController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;


    @RequestMapping(value = "info_init", method = RequestMethod.GET)
    private Map<String, Object> getShopInitInfo() {
        Map<String, Object> modelMap = new HashMap<>();
        try {
            modelMap.put("success", true);
            modelMap.put("shopCategoryList", shopCategoryService.getShopCategoryList(new ShopCategory()));
            modelMap.put("areaList", areaService.getAreaList());
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    private Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "输入的验证码错误");
            return modelMap;
        }
        // 1.接收并转化相应的参数,包括店铺信息以及图片信息
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop;
        try {
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (IOException e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }
        CommonsMultipartFile shopImg;
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) servletRequest.getFile("shopImg");
        } else {
            modelMap.put("errMsg", "上传图片不能为空");
            modelMap.put("success", false);
            return modelMap;
        }
        // 2、注册店铺
        if (shop != null && shopImg != null) {
            PersonInfo owner = new PersonInfo();
            // Session TODO
            owner.setUserId(1L);
            shop.setOwner(owner);
            ShopExecution shopExecution;
            try {
                shopExecution = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
                if (shopExecution.getState() == ShopStateEnum.CHECK.getState()) {
                    modelMap.put("success", true);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", shopExecution.getStateInfo());
                }
            } catch (IOException | ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺信息");
        }
        return modelMap;
    }
}


正在回答

登陆购买课程后可参与讨论,去登陆

4回答

同学你好,建议同学查看debug时,formData.append()这句代码中,verifyCodeActual是否有值,如:

http://img1.sycdn.imooc.com//climg/5f48e2140939a58705990056.jpg

如果这里有值,建议同学先将验证码判断注释掉,继续向后执行,查看shopStr的值是否传入到后台。

祝:学习愉快~

  • 慕慕4125024 提问者 #1
    verifyCodeActual是有值的,shopStr没有值
    2020-08-28 20:32:25
  • 慕慕4125024 提问者 #2
    代码是没有问题的,我没有在pom.xml里配置commons-fileupload依赖和在spring-web里配置文件上传解析器所以没有接收到数据,我再往后看一下视频就知道了,结果从昨天下午搞到现在。。。
    2020-08-29 10:51:28
提问者 慕慕4125024 2020-08-28 22:42:55

http://img1.sycdn.imooc.com//climg/5f49157f0976259319221032.jpg

http://img1.sycdn.imooc.com//climg/5f49157f0956434219221032.jpg

http://img1.sycdn.imooc.com//climg/5f4915c9099c188407140474.jpgrequest里不知道为什么好像没有保存key为shopStr的值,而且ajax发送的是post请求,为什么url里会有“?”,接收不到数据是不是和这个有关系?

提问者 慕慕4125024 2020-08-28 19:53:09

http://img1.sycdn.imooc.com//climg/5f48eefa097d5ff419221032.jpg

http://img1.sycdn.imooc.com//climg/5f48eefa09a4a48319221032.jpg

verifyCodeActual是有值的,shopStr没有值,这要怎么办啊?

提问者 慕慕4125024 2020-08-28 17:55:15
package com.imooc.o2o.util;

import javax.servlet.http.HttpServletRequest;

public class HttpServletRequestUtil {

    public static int getInt(HttpServletRequest request, String key) {
        try {
            return Integer.parseInt(request.getParameter(key));
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static long getLong(HttpServletRequest request, String key) {
        try {
            return Long.parseLong(request.getParameter(key));
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static double getDouble(HttpServletRequest request, String key) {
        try {
            return Double.parseDouble(request.getParameter(key));
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static boolean getBoolean(HttpServletRequest request, String key) {
        try {
            return Boolean.parseBoolean(request.getParameter(key));
        } catch (Exception e) {
            return false;
        }
    }

    public static String getString(HttpServletRequest request, String key) {
        try {
            String result = request.getParameter(key);
            if (result != null) {
                result = result.trim();
            }
            if ("".equals(result)) {
                result = null;
            }
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}


问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师