简体   繁体   中英

Can JavaScript send an HTTP request to web container Servlet?

I have a web application that currently hosts an applet in a web page. The applet connects to a Tomcat Servlet and sends requests. It would be more convenient for some environments if my solution could use Javascript instead of Java applets on the client. But this would require Javascript to send a POST to the Tomcat Servlet.

The web pages are served by the same web server - and actually the same Tomcat instance. But the applet sends requests to a DIFFERENT Servlet.

The Javascript basically would need to query the Servlet periodically and based on responses call a javascript function.

Would that be possible?

If so, any pointers on how to get started?

Yes, JavaScript can send POST requests to arbitrary web servers. If you have control of the servlet you can avoid all cross-site scripting restrictions by setting access-control-allow-origin properties.

AJAX is a term in the web community that refers to JavaScript + HTTP requests. I recommend this AJAX tutorial from MDN. I also recommend jQuery's AJAX library .


Some versions of Internet Explorer will give you trouble even if the server is set up correctly. Here's a JS function I use to cover all the browsers:

/**
 * Wraps jQuery's AJAX, adds X-Domain support for IE
 */
function xDomainAJAX (url, settings) {
  if ($.browser.msie && parseInt($.browser.version, 10) >= 8 && XDomainRequest) {
    // use ms xdr
    var xdr = new XDomainRequest();
    xdr.open(settings.type, url + '?' + $.param(settings.data));
    xdr.onprogress = function() {};
    xdr.onload = function() {
      settings.success(xdr.responseText);
    };
    xdr.onerror = settings.error;
    xdr.send();
  } else {
    // use jQuery ajax
    $.ajax(url, settings);
  }
}

Supporting "CORS" Cross-origin resource sharing on server will let you browser side script to call other server.

There are also older methods like JSONP or having page on target domain in IFrame on main page with communicating between 2 pages via window.PostMessage / IFrame name.

And if you don't need response - POST or GET can be executed to any domain.

This is definitely possible. I would suggest using jQuery, as it has this functionality in an easy to use function: http://api.jquery.com/jQuery.post/ . Note that this link has examples using $.post() and $.ajax(). Both are valid, $.post is just a shorthand version of $.ajax.

Note in both examples, you give it a callback function to handle the response.

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