简体   繁体   中英

Trying to post more than one variable via xmlhttprequest of ajax to the controller

In my java application. I am trying to post more two javascript variable to via a xmlhttp post request of ajax but it is returning error 400. Ordinarily, if I comment out one of the post variables, then it posts successfully but on adding it, throws error. This is my attempt:

function sendChat() {
        var message = document.getElementById('new-input').value.trim();
        var noteVal = "mp3",
                xhr = new XMLHttpRequest();

        ....

        alert(noteVal);
        xhr.send(encodeURI('message=' + message));
        xhr.send(encodeURI('noteVal=' + noteVal)); //if I comment this out then everything is fine
    }

this is the spring controller to receive the post arguments

@ResponseBody
    @RequestMapping(value = "/post-data", method = RequestMethod.POST)
    public ModelAndView postData(HttpServletRequest request,
                           HttpServletResponse response,
                           @RequestParam String message,
                           @RequestParam String noteVal,

Please how can I post more than one variables to the controller method via XMLHttpRequest

You can only send once, so you send both values

xhr.send('message=' + encodeURI(message) + '&noteVal=' + encodeURI(noteVal));

or sending formData

var data = new FormData();
data.append('message', message);
data.append('noteVal', noteVal);

xhr.send(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM