gpt4 book ai didi

javascript - 单击html中的链接没有给出响应

转载 作者:行者123 更新时间:2023-11-30 19:39:30 25 4
gpt4 key购买 nike

在过去的 2 周里,我一直在努力让它工作,但我似乎找不到问题所在。当我点击一个用户与之聊天时,似乎并没有在两者之间创建聊天室。我已经遵循了那个教程 https://pusher.com/tutorials/chat-aspnet/但编辑了一些东西,比如我的数据库。调试后,当我单击其中一个用户链接时,它似乎没有执行任何操作。

我试过重命名一切并重新开始

我使用 javascript 的 View :

<div class="container">
<div class="row">
<div class="col-xs-12 col-md-3">
<aside class="main visible-md visible-lg">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default users__bar">
<div class="panel-heading users__heading">
Contacts (@ViewBag.allUsers.Count)
</div>
<div class="__no__chat__">
<p>Select a contact to chat with</p>
</div>
<div class="panel-body users__body">
<ul id="contacts" class="list-group">

@foreach (var user in @ViewBag.allUsers)
{
<a class="user__item contact-@user.Id" href="#" data-contact-id="@user.Id" data-contact-name="@user.FirstName">
<li>
<div class="avatar">
<img src="@Url.Content("~/Content/no_avatar.png")">
</div>
<span>@user.FirstName</span>
<div class="status-bar"></div>
</li>
</a>
}
</ul>
</div>
</div>
</div>
</div>
</aside>


</div>
<div class="col-xs-12 col-md-9 chat__body">
<div class="row">
<div class="col-xs-12">
<ul class="list-group chat__main"></ul>
</div>
<div class="chat__type__body">
<div class="chat__type">
<textarea id="msg_box" placeholder="Type your message"></textarea>
<button class="btn btn-primary" id="sendMessage">Send</button>
</div>
</div>
<div class="chat__typing">
<span id="typerDisplay"></span>
</div>
</div>
</div>
</div>
</div>
<script>
let currentContact = null; // Holds current contact
let newMessageTpl =
`<div>
<div id="msg-{{id}}" class="row __chat__par__">
<div class="__chat__">
<p>{{body}}</p>
<p class="delivery-status">Delivered</p>
</div>
</div>
</div>`;

// select contact to chat with
$('.user__item').click(function(e) {
e.preventDefault();

currentContact = {
Id: $(this).data('contact-id'),
FirstName: $(this).data('contact-name'),
};

$('#contacts').find('li').removeClass('active');

$('#contacts .contact-' + currentContact.Id).find('li').addClass('active');
getChat(currentContact.Id);
});

// get chat data
function getChat(contact_id) {
$.get("/contact/conversations/" + contact_id)
.done(function(resp) {
var chat_data = resp.data || [];
loadChat(chat_data);
});
}

...

我的 Controller :

public ActionResult Index()
{
if (Session["UserID"] == null)
{
return Redirect("/");
}

//var currentUser = (Models.tblUser) Session["UserID"];


using (var db = new Models.ChatContext())
{
int currentUserId = (int) Session["UserID"];
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
ViewBag.allUsers = db.Users.Where(u => u.Id != currentUser.Id).ToList();
ViewBag.currentUser = currentUser;
}


return View();
}

public JsonResult ConversationWithContact(int contact)
{
if (Session["UserID"] == null)
{
return Json(new {status = "error", message = "User is not logged in"});
}

var currentUser = (Models.tblUser)Session["UserID"];

var conversations = new List<Models.tblMessage>();

using (var db = new Models.ChatContext())
{
conversations = db.Conversations.Where(c => (c.receiverId == currentUser.Id
&& c.senderId == contact) ||
(c.receiverId == contact
&& c.senderId == currentUser.Id))
.OrderBy(c => c.created_at)
.ToList();
}

return Json(
new {status = "success", data = conversations},
JsonRequestBehavior.AllowGet
);
}

我的消息模型和聊天上下文:

public class ChatContext : DbContext
{
public ChatContext() : base("TrinityEntities")
{
}

public static ChatContext Create()
{
return new ChatContext();
}

public DbSet<tblUser> Users { get; set; }
public DbSet<tblMessage> Conversations { get; set; }
}

public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}

public enum messageStatus
{
Sent,
Delivered
}

public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}

我的路由配置:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
);

//routes.MapRoute(
// name: "Default",
// url: "",
// defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
//);

routes.MapRoute(
name: "Profile",
url: "profile",
defaults: new { controller = "Profile", action = "Index" }
);

routes.MapRoute(
name: "Home",
url: "Home",
defaults: new { controller = "Home", action = "Index" }
);

routes.MapRoute(
name: "ChatRoom",
url: "chat",
defaults: new { controller = "Chat", action = "Index" }
);

routes.MapRoute(
name: "GetContactConversations",
url: "contact/conversations/{contact}",
defaults: new { controller = "Chat", action = "ConversationWithContact", contact = "" }
);

routes.MapRoute(
name: "PusherAuth",
url: "pusher/auth",
defaults: new { controller = "Auth", action = "AuthForChannel" }
);

routes.MapRoute(
name: "SendMessage",
url: "send_message",
defaults: new { controller = "Chat", action = "SendMessage" }
);

routes.MapRoute(
name: "MessageDelivered",
url: "message_delivered/{message_id}",
defaults: new { controller = "Chat", action = "MessageDelivered", message_id = "" }
);

最佳答案

在 ChatContext 位下方的说明中,您可能错过了一行:

"To retrieve the messages, we will create a route for /contact``/conversations/{contact}. This route will accept a contact ID, retrieve messages between the current user and the contact, then return the messages in a JSON response. "

目前,在 javascript 中,getChat() 函数向 /contact/conversation/{contactId} 发送请求。对于 MVC 项目,默认路由格式是 /{controllerName}/{actionName}/{parameter}。因此,您的 javascript 中的调用当前会查找名为 ContactController 的 Controller ,然后在该 Controller 上执行名为 Conversation 的操作。如您所知,这些目前不存在于您的项目中,因此您需要在 routeConfig 中设置一个路由来理解传入的请求并将其指向您希望它去的地方:

routes.MapRoute(
name: "ChatRoom",
url: "chat/conversation/{contact}",
defaults: new { controller = "Chat", action = "ConversationWithContact" }
);

这应该可以解决您的问题。但是,正如您刚刚学习的那样,我认为值得一提的是,尽管对于小型应用程序来说很好,但是一旦应用程序增长,像这样手动映射路由可能会导致混淆,因为您可能有数十条不同名称的路由指向您的 Controller 和操作本来猜不出来的。如果代码符合某种标准,例如 /controllerName/actionName

,则更容易维护和理解代码的流程

关于javascript - 单击html中的链接没有给出响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com