How to get a json from server http://localhost:2323
if $.Ajax in jQuery doesn't work. The json is generated width java class:
public class Main {
public static void main(String[] arr) {
new Main().start();
}
protected void start() {
for (;;) {
try {
Socket remote = new ServerSocket(2323).accept();//port number
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.print("{\"a\":\"A\",\"b\":\"asdf\",\"c\":\"J\"}");
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
}
that outputs {"a":"A","b":"asdf","c":"J"}. And jquery script is
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost:2323',//the problem is here
async: false,
data: {},
success: function(data) {
alert(data.a+' '+data.b+' '+data.c);
}
});
});
if url is http://localhost
, then it works, if i append an :portnumber, it doesn't work. How to read from an url:portnumber?
Thanks
Specifying port in ajax calls won't work due to Same origin policy (http://en.wikipedia.org/wiki/Same_origin_policy). Which means that URL must have the same domain and port as the server, where script's hosted.
Also, please note that this question was already asked, and is one of the first results when searching in google - Is it possible to specify a port in a ajax call
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With