zoukankan      html  css  js  c++  java
  • ajax 415

    ajax 发送post请求是出现415错误,是ajax的格式有问题,如下。

     1  $.ajax({
     2               type: 'POST',
     3               url: '/login',
     4               data: {
     5                      "username": username,
     6                      "password": password
     7                     },
     8               dataType: "json",
     9               success: function(res){
    10                     alert(res);
    11                 }
    12             });

    更正后:

     1         $.ajax({
     2               type: 'POST',
     3               url: '/login',
     4               data: {
     5                      "username": username,
     6                      "password": password
     7                     },
     8               dataType: "json",
     9               contentType:"application/json",
    10               success: function(res){
    11                     alert(res);
    12                 }
    13             });

    就这样改了之后,又来了400错误:

    Could not read document: Unrecognized token 'username': was expecting ('true', 'false' or 'null');

    当在后台使用@RequestBody来接收参数的时候,就需要在前端中ajax的参数格式为:

     1         var json = {
     2                 "username": username,
     3              "password": password
     4             }
     5         $.ajax({
     6               type: 'POST',
     7               url: '/login',
     8               data:JSON.stringify(json),
     9               dataType: "json",
    10               contentType:"application/json",
    11               success: function(res){
    12                     alert(res);
    13                 }
    14             });
    1 @RequestMapping(value="/login", method=RequestMethod.POST)
    2     public void login(@RequestBody JSONObject json)
    3     {
    4         User user = json.getObject("data", User.class);
    5         
    6         // 1、创建 HttpClient 的实例
    7         CloseableHttpClient httpClient = HttpClients.createDefault();
    8         

    要穿原生的格式的ajax的data,也不用在添加@RequestBody的注解了。需要对应着来。

    ---不要装作很努力
  • 相关阅读:
    [leetcode]Reverse Words in a String
    [leetcode]ZigZag Conversion
    [leetcode]Gray Code
    [leetcode]Permutation Sequence
    [leetcode]Next Permutation
    [leetcode]PermutationsII
    [leetcode]Add Two Numbers
    Python与PHP通过XMLRPC进行通信
    最近发现了个js传图预览的函数和大家分享下
    百度地图api2.0体验
  • 原文地址:https://www.cnblogs.com/goblinn/p/9352267.html
Copyright © 2011-2022 走看看