Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery, ajax, port number

Tags:

java

jquery

ajax

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

like image 415
user2301515 Avatar asked May 03 '13 07:05

user2301515


1 Answers

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

like image 189
Arnthor Avatar answered Sep 18 '22 22:09

Arnthor