忽略Ajax网址中的http:localhost

时间:2018-12-28 14:47:02

标签: ajax django django-channels

我正在使用django通道在我的项目中实现即时消息传递应用程序。消息框不会占据整个屏幕,因此我试图使用ajax来实现它。所面临的问题是我在ajax的url字段中以http://locahost开头。我不希望这样,因为我在ws://

上使用了ASGI和Django通道

我尝试在网址前添加“ /”

var wsStart = 'ws://';
if (loc.protocol == 'https:'){
    wsStart ='wss://';
 }
var endpoint = wsStart + loc.host;

$.ajax({
  type: 'POST',
  url:"/"+endpoint+"/messages/"+username+"/",
  data: {
  'username': username,
   csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
   },
   success: function (res, status) {
    console.log("RESOPONSE",res);
    },
    error: function (res) {
    console.log(res.status);
   }
  });

我希望该网址为ws:// localhost:8000 / messages /

我现在得到的是
http://localhost:8000/ws://localhost:8000/messages/mohitharshan123/

2 个答案:

答案 0 :(得分:1)

问题在于,您以“ /”开头的url,这意味着当前基本url附加了其他路径。请先指定网址ws:// localhost,然后再追加所需内容。

答案 1 :(得分:1)

实际上,您不能将WebSocket与AJAX或CORS一起使用,它将无法工作。

相关问题