所以我正在尝试通过 jquery post 方法与本地 java 服务器通信,但我运气不佳。我使用的邮政编码是:
$.post('localhost:5051/receive', {'plugs':client['plugins']});
其中 client['plugins'] 是一个具有确认值的字符串。
我试图接收这个的 servlet 是(所有必要的导入):
public class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BaseServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String plugins = request.getParameter("plugs");
System.out.println("HERE");
System.out.println(plugins);
}
}
似乎这个 servlet 没有从 post 方法接收到任何通信。
请注意,javascript 在我刚刚在浏览器中打开的本地 html 文件上运行。
以下是包含所有必要导入的基本服务器代码:
public class MyServer {
public static void main(String[] args) throws Exception {
Server server = new Server();
Connector connector = new SocketConnector();
connector.setPort(5051);
server.setConnectors(new Connector[]{connector});
ServletHandler handler=new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping("BaseServlet", "/receive");
server.start();
server.join();
}
}
谢谢,如果这很直观,我深表歉意。
最佳答案
当你说 $.post('localhost:5051/receive'
时,你的意思可能是 $.post('http://localhost:5051/receive'
但是这只有在您已经在使用该主机和端口时才有效(same origin policy 出于安全原因对此进行限制)所以您不妨使用相对 URI 并说 $.post('/receive'
编辑。我刚刚发现:
Note the javascript is running on a local html file I am just opening in my browser.
正如我之前所说,JS 运行的页面必须在the same host and port 上作为请求数据的 URI。
关于javascript - Jquery 与本地服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5690138/