retrieve data from servlet using jquery -
i want utilize servlet homecoming info html page using jscript , jquery get. not work , don’t see why. i’m using tomcat 7.056, servlet-api-2.5 , jquery-1.11.1.min.js
the problem in next linecode:
$.get('htp://.../servletteste2', function(responsetext) {
servlet code
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class servletteste2 extends httpservlet { public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string text = "example text"; response.setcontenttype("text/plain"); response.setcharacterencoding("utf-8"); response.getwriter().write(text); } }
html code
class="snippet-code-html lang-html prettyprint-override"><html lang="en"> <head> <title>so question 4112686</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script> $(document).ready(function() { $('#somebutton').click(function() { $('#somediv').text("hello...."); //document.location.href = "http://localhost:8080/servletteste2"; $.get('http://localhost:8080/servletteste2', function(responsetext) { $('#somediv').text("hello...."); $('#somediv').text(responsetext); }); }); }); </script> </head> <body> <button id="somebutton">press here</button> <div id="somediv"></div> </body> </html>
mapping
<servlet> <servlet-name>servletteste2</servlet-name> <servlet-class>servletteste2</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletteste2</servlet-name> <url-pattern>/servletteste2/</url-pattern> </servlet-mapping>
notice if remove //
//document.location.href = "http:..../servletteste2";
the servlet work, i.e. have new page on screen “example text" on screen.
the problem
$.get('http://.../servletteste2',
returns false
document.location.href = "http://.../servletteste2";
works.
it's been while since i've used servlets problem seems related (as nomeshdesilva pointed out) cross-domain ajax problem.
check console check if have error this:
xmlhttprequest cannot load http://localhost:8080/. no 'access-control-allow-origin' header nowadays on requested resource. origin 'http://localhost' hence not allowed access.
if so, means need give permission on server indicating cross domain requests accepted.
since, in case, command code of servlet seek adding next line servlet code:
response.setheader("access-control-allow-origin", "*");
important note: wildcard allows domain send requests host. after checking fixes problem, it's recommended replace "*" specific domain you'll sending requests.
jquery servlets
No comments:
Post a Comment