Home >Web Front-end >JS Tutorial >Introducing several methods of ajax and background data transmission in Spring

Introducing several methods of ajax and background data transmission in Spring

coldplay.xixi
coldplay.xixiforward
2020-12-04 16:26:327827browse

ajaxThe column introduces the method of transmitting data with the background

Introducing several methods of ajax and background data transmission in Spring

Recommended (free): ajax

I recently encountered a problem when writing ajax and transmitting data to the background. I want ajax to transmit the data to the background in the form of json, and the background will receive it in the form of map, and then return the data in the form of map. . However, I kept encountering the error message (*) (@415 Unsupported media type) at the front desk, and then I finally solved it after consulting the information. Here is a summary of several ways to transmit data between ajax and the background. The solutions to the above problems are at the end of this article.


1. Put the data in the url and pass it
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById/"+id,//参数放在url中
success:function(data){ alert(data);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
Backend:

e03b848252eb9375d56be284e690e873ffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById/{id}")
@ResponseBody
    public Map14bd1badcdee783757181db757c9943f getPeopleById(@PathVariable("id") int id) {
        //@PathVariable("id") 如果参数名与url定义的一样注解可以不用定义("id")
        System.out.println(id);
        Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
        return map;
    }
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec

2. Put the data into data
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById",
data: {id:id},
success:function(data){ alert(data.result);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
Backend (two methods ):

e03b848252eb9375d56be284e690e873ffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    return map;
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec


@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    // 这里得到的都是字符串得转换成你需要的类型
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    return map;
}

1cd55414ff5abdfea5dd958e7e547fdd

3. Transmit with json (the situation mentioned at the beginning)
js (including some common ajax parameter explanations):
<code>
var id = $("#id").val();
$.ajax({
type: "POST",//请求类型
timeout:10000,  //设置请求超时时间(毫秒)
async:ture,//是否为异步请求
cache:false,//是否从浏览器缓存中加载请求信息。
url: "/IFTree/people/getPeopleById",
contentType: "application/json;charset=UTF-8",//提交的数据类型
data: JSON.stringify({id:id}),//这里是把json转化为字符串形式
dataType: "json",//返回的数据类型
success:function(data){
$("#name").val(data.result.name);
},
error:function(xhr, textStatus, errorThrown) {
}
});
});
</code>
Backend:

1417fd9caae40516c8185eb949b251edffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById", produces = "application/json")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(@RequestBody Map14bd1badcdee783757181db757c9943f body){
    System.out.println(""+body.get("id"));
    People people = peopleService.getPeopleById(Integer.valueOf((String)body.get("id")));
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    map.put("result", people);
    return map;
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec

Detailed explanation:

@RequestBody
This annotation first reads the request request Text data, then use the default configured HttpMessageConverter to parse, bind the data to the object, and then bind the object to the parameters in the controller.
@ResponseBody
This annotation is also used to convert the object returned by the Controller method into the specified format through HttpMessageConverter, and then writes it to the body data area of ​​the Response object.

Srping mvc .xml (configuration converter)

ffbe95d20f3893062224282accb13e8f

 266dae442ac9dc95e3bdec99752e3b4d
 584454ffd05c6f0e3c55641435afbafd
    4d2d13b32b6824d433e20957bf031c9c
        0efe1b6b91208fe6ccb37533ee972a52
        4309a73696dbaeac0ddd115cebb6f9b7
            9cfc82ad645e238cfb23844fcc566fb0
            b15467429256a47420d73a292704d15c
            4fd24be84f9bb50bd43e1c13351e6665
            b6b7f77ea6dcfce4539ab4f516be1876
            05da36058a5ae95ab9385e514bd64d98
            21a4cbd21ee44ffbefb7b42e6a338a11
                d0e6ed04ce081f36fe4ad23a6e2f195d
                    4309a73696dbaeac0ddd115cebb6f9b7
                        8487820b627113dd990f63dd2ef215f3application/json;charset=UTF-84b175f9a50d57c75316becd702e959dc
                    17e5453f22e09a7f163b2d4ce32c48b7
                dde4123f2ed5a21d0bae333af89830f9
            4bb0e59fd50cbfe6f6ce2215b9d9424341a073a833a1192b911b28010fe7d5f7
        17e5453f22e09a7f163b2d4ce32c48b7
    dde4123f2ed5a21d0bae333af89830f9
4bb0e59fd50cbfe6f6ce2215b9d94243

1cd55414ff5abdfea5dd958e7e547fdd
ByteArrayHttpMessageConverter: Responsible for reading Get data in binary format and write data in binary format;
StringHttpMessageConverter: Responsible for reading data in string format and writing data in binary format;
ResourceHttpMessageConverter : Responsible for reading resource files and writing resource file data;
FormHttpMessageConverter: Responsible for reading data submitted by form
MappingJacksonHttpMessageConverter: Responsible for reading and writing json format Data;
SouceHttpMessageConverter: Responsible for reading and writing data defined by javax.xml.transform.Source in xml;
Jaxb2RootElementHttpMessageConverter: Responsible for reading and writing Data in xml tag format;
AtomFeedHttpMessageConverter: Responsible for reading and writing data in Atom format;
RssChannelHttpMessageConverter: Responsible for reading and writing data in RSS format;

I only use the json converter in the project, so I need to import the json package (maven):

<code>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
</code>

Similarly, the parameters in the controller can also be received in the form of entity classes. Data,
started reporting errors (415 Unsupported media type) because the configuration file was not written correctly and the corresponding package was not imported.
If there are any deficiencies or errors, please point them out, thank you _

If you want to learn more about programming, please pay attention to the php training column !

The above is the detailed content of Introducing several methods of ajax and background data transmission in Spring. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete