Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method javaservlet in function javascript?

function ShowMessage() {
    var url = '/primes/PrimesServlet';
    var result = CQ.HTTP.eval(url);
    var i = Number(document.getElementById("input").value);
    var str = document.getElementById("test");
    // if(result.checkPrimes(i)) // Want to call here
    str.innerHTML = i + " là số nguyên tố";
    // else str.innerHTML = i + " là hợp số";
    document.getElementById("output").style.display="block";
}

public class PrimesServlet extends HttpServlet {
    public boolean checkPrimes(long n) {
        boolean _return;
        MillerRabin obj = new MillerRabin();
        _return = obj.checkPrimes(n);
        return _return;
    }
 }

I want to call the method checkPrimes(long n) from my function ShowMessage(), but I can't.

like image 765
anhhtbk Avatar asked Mar 03 '26 05:03

anhhtbk


1 Answers

I want to call method checkPrimes(long n) from function javascript "ShowMessage()" but I can't.

Yes you cannot.

Java plays on server side and javascript plays on client side.

Java needs compiled code and Javascript is just a scripting language interpreted by the browser.

What you need is just make a request to server.

That request may be

  1. form submission

  2. Ajax

Besides all with javascript you can check Prime like.

function isPrime1(n) {
    if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false; 
    var m=Math.sqrt(n);
    for (var i=2;i<=m;i++) if (n%i==0) return false;
    return true;
}

Just found here.

If you want to make a request with JavaScript, Ajax is your friend.

A great example :How to use Servlets and Ajax?

like image 83
Suresh Atta Avatar answered Mar 04 '26 20:03

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!