Home > OS >  How to get array from JavaScript to JavaController?
How to get array from JavaScript to JavaController?

Time:03-23

I am saving data of how long users hold the buttons when they are writing. Now the data is saved in const holdingTimes, but I want to add any button in html like SAVE and then send data from js to my JavaController.

html:

<div >
    <p>Write some text:</p>
    <form>
        <div >
            <textarea  rows="5" id="myInput"></textarea>
        </div>
    </form>
</div>

js:

<script>
    var pressedTime; var releasedTime; var holdingTime; 
    const holdingTimes = [];
 
    document.getElementById("myInput").addEventListener("keydown", pressedFunction);
    document.getElementById("myInput").addEventListener("keyup", releasedFunction);

    function pressedFunction() {
        pressedTime = Date.now();
    }

    function releasedFunction() {
        releasedTime = Date.now() ;
        holdingTime = releasedTime - pressedTime;
      
        holdingTimes.push(holdingTime);
    }
</script>

Any ideas how to build JavaController and SAVE button?

JavaController looks like:

@Controller
@Scope(WebApplicationContext.SCOPE_SESSION)
@RequestMapping("/getValues")

public class JavaController {

int [] holdingTimes;

@RequestMapping("/save")
    public String getData(int[] holdingTimesFromJs, Model model) {
        
        holdingTimes = holdingTimesFromJs;        

        return "redirect:/";
    }
}

CodePudding user response:

On click of button, call a Javascript function which will send an Ajax POST request to the Controller.
                
JavaScript Code:

const holdingTimes = [];
holdingTimes.push(10);
holdingTimes.push(20);
holdingTimes.push(30);
            
$.ajax({
    'url' : "/test-url",
    "data" : JSON.stringify(holdingTimes),
    'method' : "POST",
    'contentType' : 'application/json'
}).done(function(data) {
    // handling code for success response
});
            
            
Spring Controller:    

@PostMapping("/test-url")
public String testArrayUpload(@RequestBody int[] times) {
    //your logic goes here
    return "test";
}
  • Related