【问题标题】:JQuery, ajax, port numberjQuery、ajax、端口号
【发布时间】:2013-05-03 07:01:43
【问题描述】:

如果 jQuery 中的 $.Ajax 不起作用,如何从服务器 http://localhost:2323 获取 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);
            }
        }
    }
}

输出 {"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);
        }
    });
});

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

谢谢

【问题讨论】:

标签: java jquery ajax


【解决方案1】:

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

另外,请注意这个问题已经被问过了,并且是在谷歌搜索时的第一个结果之一 - Is it possible to specify a port in a ajax call

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2014-07-07
    • 2011-01-14
    • 2017-02-27
    相关资源
    最近更新 更多