javascript - Java Http server Get Post to Ajax -
i have simple http server written in java. trying achieve have javascript/ajax client there able message server. java server have able detect connection made client unable message out print server.
there button in client, upon clicking server message did not thought able send connection server. client should display "test server" upon clicking button
client
<html> <body> <h2>ajax</h2> <button type="button" onclick="loaddoc()">request data</button> <p id="demo"></p> <script> function loaddoc() { var xhttp = new xmlhttprequest(); xhttp.onreadystatechange = function() { if (xhttp.readystate == 4 && xhttp.status == 200) { document.getelementbyid("demo").innerhtml = xhttp.responsetext; } }; xhttp.open("get", "http://127.0.0.1", true); xhttp.send(); } </script> </body> </html>
server
public class javahttpserver { protected void start() { serversocket s; system.out.println("webserver starting on port 80"); try { s = new serversocket(80); } catch (exception e) { system.out.println("error: " + e); return; } system.out.println("waiting connection"); (;;) { try { socket remote = s.accept(); system.out.println("connection, sending data."); bufferedreader in = new bufferedreader(new inputstreamreader( remote.getinputstream())); printwriter out = new printwriter(remote.getoutputstream()); string str = "."; while (!str.equals("")) str = in.readline(); out.println("http/1.0 200 ok"); out.println("content-type: text/html"); out.println("server: bot"); out.println(""); out.println("<h1>test server</h2>"); out.flush(); remote.close(); } catch (exception e) { system.out.println("error: " + e); } } } public static void main(string args[]) { javahttpserver ws = new javahttpserver(); ws.start(); }
the browser rejects response because miss access-control-allow-origin http header. try add this: out.println("access-control-allow-origin: *");
Comments
Post a Comment