Karunagara
Karunagara

Reputation: 389

How to call a Java Method from JavaScript function?

I have a scenario like when user clicks on the hyperlink from the HTML page, it has to go with the ID (passed id in the onclick method of hyperlink) and call the Java method that accepts the ID parameter. Based on the ID, it returns some of the values as an Array to the Javascript function.

This is my java script function

function showTestCaseReport(testCaseId, testSteps)
{
    var jObject = Java.type('Practice.myclasses.GenerateReport');
    var stepResult = jObject.getTestStepsByCaseId(testCaseId); 
    alert(stepResult.length);
}

But its not working and not even showing alert dialog when click on the hyperlink.

Is there any way to integrate javascript function and java method?

Upvotes: 0

Views: 8581

Answers (2)

Kishor Velayutham
Kishor Velayutham

Reputation: 818

In HTML:

<a href="<c:url value="/test/${object.Id}" />" >Test</a>

In Java controller:

You have to use @PathVariable to get the ID passed.

@RequestMapping(value = "/test/{Id}", method = RequestMethod.GET)
    public String Controller(@PathVariable("Id") String Id) {
       ...
    }

You can directly hit the controller with href along with the Id.

If you want to hit the Java controller via JS Ajax. In JS: AJAX Call

 $.ajax({
        type: "POST",
        url: "test",
        data: loginData,
        success: function (result) {
            // do something.
        },
        error: function (result) {
            // do something.
        }
    });

Hope this helps..!

Upvotes: 0

HpetruAlin
HpetruAlin

Reputation: 36

You need to make a ajax call to a page where you execute you Java function and return your data back to your JS

 $.ajax({
  url: "java_page.jsp",
  data: ID
  }).done(function(data) {
  //Do what you need with data(your array) hear
  });

PS. the best practice is to return a JSON format data so your java code should return JSON

Upvotes: 1

Related Questions