java JQuery、ajax、端口号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16353393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:42:39  来源:igfitidea点击:

JQuery, ajax, port number

javajqueryajax

提问by user2301515

How to get a json from server http://localhost:2323if $.Ajax in jQuery doesn't work. The json is generated width java class:

http://localhost:2323如果 jQuery 中的 $.Ajax 不起作用,如何从服务器获取 json 。json是生成宽度的java类:

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

输出 {"a":"A","b":"asdf","c":"J"}。而 jquery 脚本是

$(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?

如果 url 是http://localhost,那么它就可以工作,如果我附加一个:端口号,它就不起作用。如何从 url:portnumber 读取?

Thanks

谢谢

回答by Arnthor

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.

由于同源策略( http://en.wikipedia.org/wiki/Same_origin_policy),在 ajax 调用中指定端口将不起作用。这意味着 URL 必须与托管脚本的服务器具有相同的域和端口。

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

另外,请注意这个问题已经被问到,并且是在谷歌搜索时的第一个结果之一 -是否可以在 ajax 调用中指定端口