ajax发送json,为什么后台什么也得不到?

<html>

<body>

    <input  id="customerId" >
    <input  id ="address" >
    <input     id="123" type="submit" >


</body>
<script src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("#123").click(function() {
  
    $.ajax({
        type: "POST",
        url: "http://10.2.163.2:7001/chatClientService/",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(GetJsonData()),
        dataType: "json",
        success: function (message) {
            
        },
        error: function (message) {
            
        }
    });
});

function GetJsonData() {
    var json = {
        "customerId": "7800071499",
        "address": "10.2.162.2"
       
    };
    return json;
}
</script>

</html>
@Controller(value = "blackServiceAction")
@Scope("prototype")
public class BlackServiceAction extends ActionSupport {
    private static final long serialVersionUID = -5155883818336614584L;
    @Autowired
    private BlackInfoDaoImpl blackInfoDao;
    public String execute() throws ServletException, IOException {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        InputStream ins = request.getInputStream();
        
        InputStreamEntity entity = new InputStreamEntity(ins, 1024);
        String requestContent = EntityUtils.toString(entity, "utf-8");
        JSONObject requestJson = JSONObject.fromObject(requestContent);
        try {
            
            String customerId = requestJson.getString("customerId");
            String address = requestJson.getString("address");
            String result = isBlack(customerId,address);
            response.getWriter().print(result);
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }
阅读 2.2k
3 个回答

你好,Form 表单并无此属性值,你这么写还是会当做 application/x-www-form-urlencoded 来处理,发送的是 username=小华&age=18 这样的格式。

发送 JSON 格式的可以用 AJAX,设置 xhr.setRequestHeader('Content-Type', 'application/json');,然后再 send 的时候就可以这么发送:

xhr.send(JSON.stringify({
    username,
    password
}));

当然你也可以使用 jQuery,就像下面这样:

$.ajax({
    url:'user.php',
    type:'post',
    data:{
        user: '小华',
        age: 18
    }
});

给个默认值?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题