action-menu 相关问题


脚本无法在我的引导模式中工作

希望这不是一个愚蠢的问题,但我已经没有主意了...... 所以我有这个模式: 1.scala.html 希望这不是一个愚蠢的问题,但我已经没有主意了...... 所以我有这个模式: 1.scala.html <div class="feat" id="cor" data-toggle="tooltip" data-placement="bottom" title="add conference role"><div data-toggle="modal" data-target="#conf-role-menu-modal">Conference Role</div></div> <div class="modal fade" id="conf-role-menu-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body-conf-role-menu"> <script type="text/javascript"> $(function(){ $(".modal-body-conf-role-menu").load("@routes.Application.areaConferenceRole(id,idenv)"); }); </script> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> 使用模态主体中的脚本,我尝试加载此页面: 2.scala.html @(id:String, idenv:String) @Main("Add area") { <form action="@routes.Application.areaPostConferenceRole(id,idenv)" method="POST"> First Name: <input type="text" name="first_name" id="first" class="form-control"> Last Name : <input name="last_name" class="form-control"> <script type="text/javascript"> $( document ).ready(function() { // Handler for .ready() called. $( "#first" ).focus(function() { alert( "Handler for .focus() called." ); }); }); </script> </form> } 页面加载正常。我在我的模态中看到它...... 问题是我的页面 2.scala.html 中的脚本无法运行。我不明白为什么......如果我从我尝试在模态中加载的页面之外尝试它们,它们就会起作用...... $( document ).ready(function(){}); 永远不会在模态中到达,因为加载页面时已经触发了此事件(模态在之后加载...) 尝试直接插入脚本,如下所示: <script type="text/javascript"> $( "#first" ).focus(function() { alert( "Handler for .focus() called." ); }); </script> 当引导模式弹出时,shown.bs.modal事件将被触发。这是例子。 $('#myModal').on('shown.bs.modal', function () { $('#myInput').trigger('focus') }) Full documentation. https://getbootstrap.com/docs/4.0/components/modal/ 试试这个我已经准备好这个功能了 $('#myModal').on('shown.bs.modal', function () { // Your script here }); $(document).on('shown.bs.modal', '#myModal', function () { // Your script here });


下拉按钮在 Bootstrap 5.3 上不起作用

我正在使用 Express、EJS 和 bootstrap 制作一个网站,但下拉按钮不起作用 代码: <%- include('../includes/head') %> 我正在使用 Express、EJS 和 bootstrap 制作一个网站,但下拉按钮不起作用 代码: <%- include('../includes/head') %> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">Dropdown button</button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </div> <%- include('../includes/footer') %> 头: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <title>Title</title> </head> <body> 页脚: <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </body> </html> 当我单击按钮时,它不显示下拉菜单的内容 我不知道这是否重要/有效,但尝试将引导脚本从页脚移动到页眉,它可能基于加载顺序。


如何去除特定元素的 :hover 效果?

首页 &... <div class="menu-bar"> <ul> <li><a href="/Home/index.html"> <i class="fa fa-house"></i>Home</a> </i></li> < ul > </div> <style> .menu-bar ul li a:hover { color: black; transition: all 0.2s; border-inline-end: 2px solid; border-block-end: 2px solid; </style> 我想从 fa fa-house 的 cdn 图标中删除 :hover 效果。 <div class="menu-bar"> <ul> <li> <i class="fa fa-home"></i> <a href="/Home/index.html"> Home </a> </li> </ul> </div> <style> .menu-bar ul li a:hover { color: black; transition: all 0.2s; border-inline-end: 2px solid; border-block-end: 2px solid; } .menu-bar ul li i{ pointer-events: none; } </style> <div class="menu-bar"> <ul> <li><i class="fa fa-house"></i><a href="/Home/index.html"> Home</a> </i></li> <ul > 只需从 <i> 标签中取出 <a> 元素(图标)即可。 你可以试试这个:- <div class="menu-bar"> <ul> <li><i class="fa fa-house"><a href="/Home/index.html"> </i>Home</a> </i></li> </ul> </div> <style> .menu-bar ul li a:hover { color: black; transition: all 0.2s; border-inline-end: 2px solid; border-block-end: 2px solid; } </style>


何时切换搜索栏和徽标下降?

.navbar { 背景颜色:#F91F46; } .src-bar { 边框:0; 边框半径:5px; 概要:无; 左内边距:15px; 宽度:30vw; } .navbar { background-color: #F91F46; } .src-bar { border: 0; border-radius: 5px; outline: none; padding-left: 15px; width: 30vw; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" integrity="sha512-b2QcS5SsA8tZodcDtGRELiGv5SaKSk1vDHDaQRda0htPYWZ6046lr3kJ5bAAQdpV2mmA/4v0wQF9MyU6/pDIAg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js" integrity="sha512-WW8/jxkELe2CAiE4LvQfwm1rajOS8PHasCCx+knHG0gBHt8EXxS6T6tJRTGuDQVnluuAvMxWF4j8SNFDKceLFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <nav class="navbar navbar-expand-md fixed-top"> <div class="container-fluid"> <a class="navbar-brand ms-3" href="#"> <img src="img/Logo.avif" width="40px" class="d-inline-block" /> </a> <form role="search" class="search-bar"> <div class="input-group"> <input class="src-bar" type="search" placeholder="Search For Products" /> <button class="btn bg-white" type="submit"> <i class="fa fa-search"></i> </button> </div> </form> <div class="justify-content-end"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nav-colps" aria-controls="nav-colps" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="nav-colps"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li> <hr class="dropdown-divider" /> </li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> </div> </div> </div> </nav> 切换时,我希望折叠 div 居中。我知道原因 - 我将折叠和切换 btn 放在 justify-end div 内,因为我需要切换 btn 位置位于右侧。现在,当切换时,我的折叠位于右侧,但我希望在切换时,折叠div到中心。 当我删除 justify-end div 时,它位于左侧,但如果删除它,每个导航元素都会移动到 nav 和 md 视图中 lg 的左侧。 看起来像这样或中心 我们确实需要将 .nav-collapse 移到 justify-end 元素之外,才能在较窄的视口上获得所需的布局。 要将菜单显示在右侧,请通过 flex-grow: 1 类将 .nav-collapse 应用于 flex-grow: 0 元素,覆盖 flex-grow-0 上的默认 .nav-collapse。 为了使窄视口的链接元素居中,.navbar-nav中的元素采用垂直柔性布局,因此我们可以通过align-items: center类应用align-items-center: .navbar { background-color: #F91F46; } .src-bar { border: 0; border-radius: 5px; outline: none; padding-left: 15px; width: 30vw; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" integrity="sha512-b2QcS5SsA8tZodcDtGRELiGv5SaKSk1vDHDaQRda0htPYWZ6046lr3kJ5bAAQdpV2mmA/4v0wQF9MyU6/pDIAg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js" integrity="sha512-WW8/jxkELe2CAiE4LvQfwm1rajOS8PHasCCx+knHG0gBHt8EXxS6T6tJRTGuDQVnluuAvMxWF4j8SNFDKceLFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <nav class="navbar navbar-expand-md fixed-top"> <div class="container-fluid"> <a class="navbar-brand ms-3" href="#"> <img src="https://picsum.photos/40/40" width="40px" class="d-inline-block" /> </a> <form role="search" class="search-bar"> <div class="input-group"> <input class="src-bar" type="search" placeholder="Search For Products" /> <button class="btn bg-white" type="submit"> <i class="fa fa-search"></i> </button> </div> </form> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nav-colps" aria-controls="nav-colps" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse flex-grow-0" id="nav-colps"> <ul class="navbar-nav me-auto mb-2 mb-lg-0 align-items-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li> <hr class="dropdown-divider" /> </li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> </div> </div> </nav> 您还可以考虑通过 text-align: center 类应用 text-center,将链接元素 text 居中: .navbar { background-color: #F91F46; } .src-bar { border: 0; border-radius: 5px; outline: none; padding-left: 15px; width: 30vw; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" integrity="sha512-b2QcS5SsA8tZodcDtGRELiGv5SaKSk1vDHDaQRda0htPYWZ6046lr3kJ5bAAQdpV2mmA/4v0wQF9MyU6/pDIAg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js" integrity="sha512-WW8/jxkELe2CAiE4LvQfwm1rajOS8PHasCCx+knHG0gBHt8EXxS6T6tJRTGuDQVnluuAvMxWF4j8SNFDKceLFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <nav class="navbar navbar-expand-md fixed-top"> <div class="container-fluid"> <a class="navbar-brand ms-3" href="#"> <img src="https://picsum.photos/40/40" width="40px" class="d-inline-block" /> </a> <form role="search" class="search-bar"> <div class="input-group"> <input class="src-bar" type="search" placeholder="Search For Products" /> <button class="btn bg-white" type="submit"> <i class="fa fa-search"></i> </button> </div> </form> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nav-colps" aria-controls="nav-colps" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse flex-grow-0" id="nav-colps"> <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li> <hr class="dropdown-divider" /> </li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> </div> </div> </nav>


Rails 6 Action 邮箱和 Gmail 集成方法

Rails 6 现在附带了 Action Mailbox。文档和社区没有关于如何集成 SendGrid 等最常见服务之外的各种服务的丰富资源。 假设一个人...


无法将商品添加到购物车文件

我有一个item.php文件和cart.php文件。 我正在尝试将 item.php 文件中的商品添加到 cart.php 文件中的购物车。 我正在从名为:menu 的数据库表中提取每个项目的详细信息 对于某些...


将回调方法转换为任务

在C#中,有没有办法转换: Foo(Action onComplete); 进入: 任务 FooTask(); Foo 函数是外部库的一部分,无法修改。


在操作中检测到不可序列化的值(redux-toolkit)

在store中action的payload中,我使用File类型存储下载的文件,然后该文件将在saga中通过验证 const form = new FormData(); if (私钥 &&


测试rxjs的正确方法

我带来了《rxjs in action》这本书,刚刚完成测试部分。 测试 rxjs 代码与通常的测试不同,因为一切都是延迟加载。 在书中,他们提到了两个...


在 Github Actions 上配置工作流程摘要

我想为我的 Github Action 工作流程配置自定义摘要,类似于 RollingVersions 的做法。在查看了文档并搜索了互联网之后,这似乎并不是那么......


Odoo14 Action Server 错误 - 无法正确调用 Python 方法

我在尝试在 Odoo14 中定义操作服务器时遇到问题。目标是调用返回窗口操作的 Python 方法,因为我需要访问当前模型中的字段......


是否可以从Rails应用程序中访问DataDog trace_id

我们在 Rails 应用程序中使用 DataDog 的分布式跟踪,并希望写入trace_id(对于控制器#action),以便我们稍后可以访问 Rails 日志中的 url。我怎么能...


使用 GitHub Action Deploy 在 Docker 容器中安装 SSL 证书

我正在使用 GitHub 操作将 .NET 应用程序部署到 Docker 容器(此处定义操作以供参考)。我找到了关于将 .crt 文件复制到图像中的主题的答案,b...


.NET 恢复/构建在使用组织包在 Github Action 工作流程中调用时得到 401

我有一个 GitHub 组织,推送了一些包。它们可以通过 https://github.com/orgs/[REDACTED]/packages 访问,因此它们不仅仅是存储库。在我的一个存储库中,我尝试创建


Github Action 构建部署 Docker .Net 8 WebApi 失败 - “程序不包含适合入口点的静态‘Main’方法”

我正在尝试完成 Github 操作,以使用 Docker 构建和部署我的 .Net8 Web API 到 Kubernetes。这是我当前用于工作流程的 yml 文件: 名称:部署到 DigitalOcean Kube...


使用(首选)直接工作负载身份联合部署 GCP App Engine 和 GitHub Actions

我有一个应用程序,已使用 gcloud 应用程序部署从本地工作站成功部署。 我现在正在尝试设置 GitHub Action 以在推送时执行此操作。 参考资料是什么...


NLog 在ConfigureServices 中写入日志会导致日志在整个应用程序中丢失${aspnet-request-url} 和${aspnet-mvc-action}

我使用 NLog 在我的 Web API 应用程序上写入日志(.Net 6) 我需要写入ConfigureServices 方法内的日志。 由于此时ILogger还无法使用,所以我就用这种方式来写...


将属性值从父级用户控件传递到子级的 DependencyProperty

如何将属性(SomeProperty)从ParentUserControl上下文传递到ChildUserControl的DependencyProperty(MyDProperty)? 在 XAML 中,它应该是: 如何将 ParentUserControl 上下文中的 property (SomeProperty) 传递到 ChildUserControl 的 DependencyProperty (MyDProperty)? 在XAML中,应该是: 但是,由于某种原因,MyDProperty 永远不会使用 Parent.DataContext.SomeProperty 设置。 就我而言,我正在传递一个操作,但这并不重要。我认为问题出在绑定上。 家长用户控制: public Action RemoveEsl1 => throw new NotImplementedException(); <uc:ChildUserControl Title="ESL 1" RemoveEslAction="{Binding RemoveEsl1}" DataContext="{Binding Esl1}"/> 子用户控件: public static readonly DependencyProperty RemoveEslActionProperty = DependencyProperty.Register(nameof(RemoveEslAction), typeof(Action), typeof(ChildUserControl), new PropertyMetadata(delegate { })); public Action RemoveEslAction { get => (Action)GetValue(RemoveEslActionProperty); set => SetValue(RemoveEslActionProperty, value); } 我在这里找到了各种技巧,但没有一个适合我或有效。 回答我自己的问题(检查 ParentUserControl): 型号: public class RootModel : ViewModelBase { private ParentModel parentModel = new(); public ParentModel ParentModel { get => parentModel; set => RisePropertyChanged(ref parentModel, value); } } public class ParentModel : ViewModelBase { private ChildModel childModel = new(); public ChildModel ChildModel { get => childModel; set => RisePropertyChanged(ref childModel, value); } public string ParentModelProperty => "Correct value from ParentModel"; } public class ChildModel : ViewModelBase { private string childModelProperty = "Wrong default value from ChildModel"; public string ChildModelProperty { get => childModelProperty; set => RisePropertyChanged(ref childModelProperty, value); } } 主窗口: <Window.DataContext> <model:RootModel/> </Window.DataContext> <uc:ParentUserControl DataContext="{Binding ParentModel}"/> 家长用户控件: <uc:ChildUserControl ChildDependency="{Binding DataContext.ParentModelProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" DataContext="{Binding ChildModel}"/> 子用户控件: <StackPanel> <Label Content="Dependency property:"/> <Label Content="{Binding ChildDependency, RelativeSource={RelativeSource AncestorType=UserControl}}"/> <Separator/> <Label Content="Property:"/> <Label Content="{Binding ChildModelProperty}"/> </StackPanel> public partial class ChildUserControl : UserControl { public static readonly DependencyProperty ChildDependencyProperty = DependencyProperty.Register(nameof(ChildDependency), typeof(string), typeof(ChildUserControl), new ("Wrong default DP value from ChildUserControl")); public string ChildDependency { get => (string)GetValue(ChildDependencyProperty); set => SetValue(ChildDependencyProperty, value); } public ChildUserControl() { InitializeComponent(); } } 这就是如何将属性 (SomeProperty) 从 ParentUserControl 上下文传递到 ChildUserControl 的 DependencyProperty (MyDProperty)。


SecurityException:不允许启动服务Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (有额外功能)}

我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: 字符串SENDER_ID =“722*****53”; /** * 向 GCM 服务器异步注册应用程序。 * * 存储注册信息... 我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: String SENDER_ID = "722******53"; /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over // HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the // device will send // upstream messages to a server that echo back the message // using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } 我收到错误: 03-01 19:15:36.261: E/AndroidRuntime(3467): FATAL EXCEPTION: AsyncTask #1 03-01 19:15:36.261: E/AndroidRuntime(3467): java.lang.RuntimeException: An error occured while executing doInBackground() 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.lang.Thread.run(Thread.java:841) 03-01 19:15:36.261: E/AndroidRuntime(3467): Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startServiceAsUser(ContextImpl.java:1800) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startService(ContextImpl.java:1772) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.content.ContextWrapper.startService(ContextWrapper.java:480) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.b(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:177) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:1) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-01 19:15:36.261: E/AndroidRuntime(3467): ... 4 more 这是我的清单: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manyexampleapp" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> <uses-permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" /> <permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <application android:name="com.zoomer.ifs.BaseApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.zoomer.ifs.MainActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTop"> <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <!-- PUSH --> <!-- WakefulBroadcastReceiver that will receive intents from GCM services and hand them to the custom IntentService. The com.google.android.c2dm.permission.SEND permission is necessary so only GCM services can send data messages for the app. --> <receiver android:name="com.example.gcm.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.example.manyexampleapp" /> </intent-filter> </receiver> <service android:name="com.example.gcm.GcmIntentService" /> <activity android:name="com.example.gcm.DemoActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- DB --> <activity android:name="com.example.db.DbActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.http.RestGetActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > </activity> <activity android:name="com.example.fb.FacebookLoginActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SendFeedbackActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.zoomer.general.SearchNearbyOffersActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.manyexampleapp.StoresListActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb.ShareActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.notifications.NotificationsActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb2.no_use.MainActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.zoomer.offers.OffersListActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SearchNearbyOffersActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <service android:name="com.example.geo.LocationService" android:enabled="true" /> <receiver android:name="com.example.manyexampleapp.BootReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="com.example.manyexampleapp.LocationService.LOCATION_BROAD_MSG" /> </intent-filter> </receiver> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" /> </application> </manifest> 改变 <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> 到 <!-- This app has permission to register and receive data message. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 您收到异常是因为您尚未定义所需的权限 如果应用程序开发后安装了播放服务, 可能会发生 com.google.android.c2dm.permission.RECEIVE 权限已被授予但 android 仍在抱怨同样的错误。 在这种情况下,您必须完全重新安装开发的应用程序才能使此权限发挥作用。 我认为你必须检查 Kotlin 版本兼容性。


使用php以动态形式考虑用户输入

考虑我有一个像这样的简单表格: 考虑我有一个像这样的简单表格: <form method="post" action="index.php"> <input id='textsearch' type="text" placeholder="Enter a character" name="search"> <button onclick="addfields()">Add</button> </form> 此处,当用户单击“添加”按钮时,会触发 onclick 事件并激活 addfields() 功能。在该函数中,我设法在此表单中添加一个输入字段,表单现在如下所示: <form method="post" action="index.php"> <input id='textsearch' type="text" placeholder="Enter a character" name="search"> <input id='textsearch_1' type="text" placeholder="Enter a character" name="search_1"> <button onclick="addfields()">Add</button> </form> 但是,出现了一个问题。如果我使用 php 来访问这些变量,我可以使用这样的东西: <?php $first_char=$_POST["search"]; $second_char=$_POST["search_1"]; ?> 但是它到哪里结束呢?我事先不知道用户创建了多少字段并在这些字段中输入了数据。那么有什么办法可以解决呢? 注意:我知道许多用户不赞成使用 onclick() 功能。我仍然坚持这个不好的使用习惯。对此表示歉意。谢谢。 你可以尝试这个概念 HTML 表单 <form method="post" action="index.php"> <input id='textsearch' type="text" name="search[]"> <input id='textsearch_1' type="text" name="search[]"> <button onclick="addfields()">Add</button> </form> PHP <?php $search_text_array=$_POST["search"]; print_r($search_text_array); ?> 你应该得到这个 PHP 结果 Array ( [0] => textsearch [1] => textsearch_1 ) 在此示例中,javascript 使用onclick() 不相关,但解释如何获取 PHP 部分


NextJS 中 useFormStatus() 始终为 false

我尝试使用 useFormStatus() 在提交表单并等待获取数据时动态更改 UI。 我有一个像这样的表单组件 函数 onSubmit(数据:z.infer 我正在尝试使用 useFormStatus() 在提交表单并等待获取数据时动态更改 UI。 我有一个像这样的表单组件 function onSubmit(data: z.infer<typeof FormSchema>) { requestImg(data).then((imageStringify) => { const binaryData = Buffer.from(imageStringify.image); const imageBase64 = URL.createObjectURL( new Blob([binaryData.buffer], { type: "image/jpeg" } /* (1) */) ); setOpen(true); setSource(imageBase64); }); } if (isDesktop) { return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6" > ... 其中 requestImg(data) 是服务器操作。 然后,我将 Button 组件嵌套在不同的 Button.tsx 文件中的 <form> 中 import { useFormStatus } from "react-dom"; import { Button } from "@/components/ui/button"; export default function ButtonSub() { const { pending } = useFormStatus(); console.log(pending); return ( <Button className="w-full" type="submit" aria-disabled={pending}> {pending ? "Processing..." : "Submit"} </Button> ); } 问题是,当我单击提交时,按钮文本不会更改为“正在处理...” 编辑 似乎仅当您在表单上使用操作关键字时才有效。我试过了 <form action={async (formData: FormData) => { requestImg(formData).then((imageStringify) => { const binaryData = Buffer.from(imageStringify.image); const imageBase64 = URL.createObjectURL( new Blob([binaryData.buffer], { type: "image/jpeg" } /* (1) */) ); setSource(imageBase64); setOpen(true); }); }} className="w-2/3 space-y-6" > 但是现在使用 byte8Array 生成的图像已损坏。 我有一个带有动态 src 的图像,其中充满了 const [source, setSource] = useState(""); <img src={source}/> 似乎只有在您使用 action 关键字时才有效 形式。 确实如此。 useFormStatus 必须在表单的子组件内使用,它可以监视服务器操作的状态变化。但据我所知,它会监听 action。 action 定义提交后表单数据的服务器端目的地。在服务器操作的上下文中,服务器操作向当前 URL 发出 post 请求。所以它没有监听表单 onSubmit,这就是为什么你的第一个代码执行不起作用。 现在服务器操作在服务器上下文中运行,它们在服务器上执行,但setState是客户端特定的代码


即使在 Angular 中禁用按钮也能调用方法

我有一个按钮,根据 Angular 中的某些条件被禁用。即使按钮被禁用,我也想启用 onclick 功能。请找到以下代码: 我有一个按钮,根据 Angular 中的某些条件被禁用。即使按钮被禁用,我也想启用 onclick 功能。请找到以下代码: <button *ngIf="overrideSplitByAccountEnabled && (!overrideSplitByaccountListOfAcc && !overrideSplitByAccountGroupValue) || ((isStartTimeInputPresent && !isValidStartTimestamp) || (isEndTimeInputPresent && !isValidEndTimestamp))" type="button" class="btn btn-primary" (click)="validateCustomReRunParameters()" disabled> <i class="glyphicon glyphicon-send" ></i> Send action </button> 即使按钮被禁用,我也想启用单击validateCustomReRunParameters() 我尝试单击,但由于按钮被禁用而无法工作。 您可以将 div 包裹在 button 周围,并将单击事件附加到该 div。如果禁用该按钮,包装器 div 将采用 button 的宽度和高度。当用户点击禁用的 button 时,将触发 div 事件。如果启用 button,div 的宽度和高度将设置为 0。 像这样的东西: <div (click)="validateCustomReRunParameters()"> <button *ngIf="overrideSplitByAccountEnabled && (!overrideSplitByaccountListOfAcc && !overrideSplitByAccountGroupValue) || ((isStartTimeInputPresent && !isValidStartTimestamp) || (isEndTimeInputPresent && !isValidEndTimestamp))" type="button" class="btn btn-primary" (click)="validateCustomReRunParameters()" disabled> <i class="glyphicon glyphicon-send" ></i> Send action </button> </div>


如何使用 Bootstrap 5 将嵌入水平居中

我正在尝试使用上面的图像进行集中输入。我按照位置文档进行操作,但不知何故图像没有水平集中: 代码: 我正在尝试使用上面的图像进行集中输入。我按照位置文档进行操作,但不知何故图像没有水平集中: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title --> <title>Title</title> <!-- Css --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <div class="container position-absolute top-50 start-50 translate-middle"> <embed class="logo" src="https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Logo"> <form action="/streams" method="POST"> <div class="input-group"> <input class="form-control border-danger border-5" type="text" aria-describedby="start-button"> <button class="btn btn-danger" type="submit" id="start-button">Click</button> </div> </form> </div> </body> </html> 我尝试手动执行此操作并使用 display flex,但没有成功。 使用text-center链接 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title --> <title>Title</title> <!-- Css --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <div class="container text-center"> <embed class="logo " src="https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Logo"> <form action="/streams" method="POST"> <div class="input-group"> <input class="form-control border-danger border-5" type="text" aria-describedby="start-button"> <button class="btn btn-danger" type="submit" id="start-button">Click</button> </div> </form> </div> </body> </html>


Laravel 购物车页面,表单内有一个表单,用于处理删除和提交数据更新数据库

我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么? 根据图片,我给出的蓝色圆圈是一个表格 我的刀片代码 我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么?根据图片我给出的蓝色圆圈是一个表格我的刀片代码<table class="table"> <thead> <tr> <th scope="col">No</th> <th scope="col">Nama Barang</th> <th scope="col">Quantity</th> <th scope="col">Action</th> </tr> </thead> <tbody> @php $no = 1; @endphp @forelse ($permintaans as $b) <tr> <td>{{ $no ++ }}</td> <td> {{ $b->nama_kategori }} {{ $b->nama_atk }} </td> <td> <form action="{{ route('permintaan.update', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('PUT') <div class="input-group input-group-sm mb-3"> <input type="number" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" name="satuan_permintaan" min="0" max={{ $b->stok }} required> <span class="input-group-text" id="inputGroup-sizing-sm">{{ $b->subsatuan_atk }}</span> </div> </td> <td> <form action="{{ route('permintaan.destroy', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('DELETE') <button type="submit" class="btn custom2-btn"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="red" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/> <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/> </svg></button> </form> </td> </tr> @empty @endforelse </tbody> </table> 我的控制器public function store(Request $request) { $task = new Permintaan(); $task->atk_id = $request->input('atk_id'); $task->proses = 'Proses'; if (Permintaan::where('atk_id', $task->atk_id)->exists()){ return redirect('/atk/permintaan')->with(['info' => 'ATK Sudah Dalam Permintaan']); } else{ $task->save(); return redirect()->route('permintaan.index'); } } public function destroy($id) { $permintaan = Permintaan::find($id); $permintaan->delete(); return redirect()->route('permintaan.index'); } 我要处理删除并提交数据更新数据库 在开始销毁表单之前关闭更新表单第一个表单标签(缺少)。


如何捕获 React-Bootstrap 下拉列表的值?

我弄清楚了如何使用react-bootstrap来显示下拉列表: 我想出了如何使用react-bootstrap来显示下拉列表: <DropdownButton bsStyle="success" title="Choose" onSelect={this.handleSelect} > <MenuItem key="1">Action</MenuItem> <MenuItem key="2">Another action</MenuItem> <MenuItem key="3">Something else here</MenuItem> </DropdownButton> 但是我该如何编写 onSelect 的处理程序来捕获正在选择的选项呢?我尝试了这个,但不知道里面写什么: handleSelect: function () { // what am I suppose to write in there to get the value? }, 还有,有没有办法设置默认选择的选项? onSelect函数传递所选值 <DropdownButton title='Dropdowna' onSelect={function(evt){console.log(evt)}}> <MenuItem eventKey='abc'>Dropdown link</MenuItem> <MenuItem eventKey={['a', 'b']}>Dropdown link</MenuItem> </DropdownButton> 在这种情况下,如果您选择第一个选项,则会打印“abc”,在第二个选项中您可以看到也可以传入一个对象。 所以在你的代码中 handleSelect: function (evt) { // what am I suppose to write in there to get the value? console.log(evt) }, 我不确定默认值是什么意思,因为这不是一个选择 - 按钮文本是标题属性中的任何内容。如果你想处理默认值,你可以在值为 null 时设置一个值。 您忘记提及 eventKey 作为第二个参数传递,这是获取您单击的值的正确形式: handleSelect: function (evt,evtKey) { // what am I suppose to write in there to get the value? console.log(evtKey) }, 您可能需要针对您的情况使用 FormControl >> 选择组件: <FormControl componentClass="select" placeholder="select"> <option value="select">select</option> <option value="other">...</option> </FormControl> 您应该按如下方式更改handleSelect签名(在组件类中): handleSelect = (evtKey, evt) => { // Get the selectedIndex in the evtKey variable } 要设置默认值,您需要使用 title 上的 DropdownButton 属性 参考:https://react-bootstrap.github.io/components/dropdowns/


如何使用DomDocument通过id获取值?

我正在尝试使用 DomDocument 获取下面表单的值,但到目前为止仍然失败 我正在尝试使用 DomDocument 获取下面表单的值,但到目前为止仍然失败 <?php $string ='<form action="profile" method="post" enctype="multipart/form-data"> <input type="hidden" name="id_user" id="id_user" value="123"> <input type="hidden" name="logo" id="logo" value="path/to/logo1.png"> <input type="hidden" name="status" id="status" value="Ok"> <input type="submit" value="PROFILE"> </form>'; ?> 这种情况下如何正确使用DomDocument? 我正在尝试下面的代码 $dom = new DomDocument(); $dom->loadHTML($string); $dom->getElementById("id_user"); 我期望得到 123 作为返回值 DomDocument 有点麻烦,但如果您遵循文档,您就可以到达那里。我找到了这条路线: $dom->getElementById("id_user")->attributes->getNamedItem("value")->value 返回: 123 参见:https://onlinephp.io/c/c37dc 可能还有其他方法可以做到同样的事情。


ASP.NET MVC 项目模板在移动设备上无法调整为 100%

我不明白为什么 Web .Net MVC 项目上的默认模板没有在移动设备中调整为 100% 宽度。 我在视图上使用数据表: @模型IEnumerable 我不明白为什么 Web .Net MVC 项目上的默认模板没有在移动设备中调整为 100% 宽度。 我在视图上使用数据表: @model IEnumerable<iziConference.Models.EventAttendee> <h2>Participantes.</h2> <br /> <button><a style="text-decoration: none" href='@Url.Action("Create", new { eventId = ViewBag.EventId })'>Criar Participante</a></button> <button id="at-btn-refresh"> Actualizar</button> <input id="eventId" type="hidden" value="@ViewBag.EventId"> <table id="at-attendees-list" cellpadding="10" border="1" class="row-border stripe"> <thead> <tr> <th>ID</th> <th>Tipo</th> <th>Nome</th> <th>Email</th> <th>Estado </th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr id="[email protected]_Id"> <td style="padding: 5px"> @Html.DisplayFor(modelItem => item.Attendee.Id) </td> <td> @Html.DisplayFor(modelItem => item.AttendeeType) </td> <td> @Html.DisplayFor(modelItem => item.Attendee.Name) </td> <td> @Html.DisplayFor(modelItem => item.Attendee.Email) </td> <td> @if (item.IsActive) { <button id="[email protected]_Id" class="at-btn-active-state active" data-attendee-id="@item.Attendee_Id" data-attendee-name="@item.Attendee.Name" data-active-new-state="false" data-show-confirmation-alert="true">Desactivar</button> } else { <button id="[email protected]_Id" class="at-btn-active-state inactive" data-attendee-id="@item.Attendee_Id" data-attendee-name="@item.Attendee.Name" data-active-new-state="true" data-show-confirmation-alert="true">Activar</button> } </td> </tr> } </tbody> </table> 由脚本加载: var _atteendeesList = "at-attendees-list"; $("#" + _atteendeesList).DataTable({ "paging": false, "info": false, "language": { "search": "Pesquisar:", "info": "Participantes inscritos: _PAGES_" } }); 使用默认的_Layout.cshtml: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>izigo Conference - Gestor de Conteúdos</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header> <div class="content-wrapper"> <section id="login"> @Html.Partial(MVC.Account.Views._LoginPartial) </section> <div style="padding: 10px;"> @if (Request.IsAuthenticated) { <nav> <ul id="menu"> <li>@Html.ActionLink("Home", MVC.Home.Index())</li> <li>@Html.ActionLink("Participantes", MVC.Attendee.Index())</li> <li>@Html.ActionLink("Check-in", MVC.Checkin.Index())</li> </ul> </nav> } </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer style="padding-left: 25px;"> <div class="content-wrapper"> <div class="float-left"> <p>&copy; @DateTime.Now.Year - <a href="https://www.izigo.pt/conference" target="_blank">izigo Conference</a> - <i>Powered by</i><a href="https://www.izigo.pt" target="_blank">izigo.pt</a></p> </div> </div> </footer> @Scripts.Render("~/bundles/jquery", "~/bundles/iziconference") @RenderSection("scripts", required: false) </body> </html> 研究了 dataTables 库的选项后,我找到了一个创建响应式解决方案的选项: 我已经包含了响应表结构和columnDefs的选项,以选择哪些选项在移动设备中保持可见: $("#" + _atteendeesList).DataTable({ "responsive": true, "columnDefs": [ { responsivePriority: 1, targets: 0 }, { responsivePriority: 2, targets: -1 } ], "paging": false, "info": false, "language": { "search": "Pesquisar:", "info": "Participantes inscritos: _PAGES_" } }); 我还必须在捆绑包中包含数据表扩展的 js 和 css 响应式库(可在此处下载:https://datatables.net/download/): bundles.Add(new ScriptBundle("~/bundles/iziconference").Include( "~/Content/Scripts/datatables.min.js", "~/Content/Scripts/dataTables.responsive.min.js")); // add-on bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/Styles/datatables.min.css", "~/Content/Styles/responsive.dataTables.min.css"));


Struts 2 与 Apache Shiro 集成时如何显示结果页面

使用: struts2 2.5.10, 春天 4.x, struts2-spring-插件2.5.10, 希罗1.4.0, Shiro-Spring 1.4.0。 网络.xml: 使用: struts2 2.5.10, 春季 4.x, struts2-spring-插件2.5.10, 四郎1.4.0, shiro-spring 1.4.0. web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- shiro filter mapping has to be first --> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> beanx.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean name="loginAction" class="example.shiro.action.LoginAction" > </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = authc /logout = logout /* = authc </value> </property> </bean> <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm"> <property name="resourcePath" value="classpath:shiro.ini" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="iniRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans> struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" extends="struts-default"> <action name="list" class="loginAction" method="list"> <result name="success">/success.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts> index.jsp: <body> <s:action name="list" /> </body> login.jsp 看起来像: <form name="loginform" action="" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr> <td>Username:</td> <td><input type="text" name="username" maxlength="30"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" maxlength="30"></td> </tr> <tr> <td colspan="2" align="left"><input type="checkbox" name="rememberMe"><font size="2">Remember Me</font></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td> </tr> </table> </form> LoginAction.list(): public String list() { Subject currentUser = SecurityUtils.getSubject(); if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal()); System.out.println("You are authenticated!"); } else { System.out.println("Hey hacker, hands up!"); } return "success"; } shiro.ini: [users] root=123,admin guest=456,guest frank=789,roleA,roleB # role name=permission1,permission2,..,permissionN [roles] admin=* roleA=lightsaber:* roleB=winnebago:drive:eagle5 index.jsp、login.jsp、success.jsp放在webapp下 我想要的是:输入LoginAction.list()需要进行身份验证,如果登录成功,则运行LoginAction.list()并返回"success"然后显示定义为Struts操作结果的success.jsp。 现在登录成功后可以执行LoginAction.list(),但是success.jsp不显示,浏览器是空白页面。 为什么? 我找到了原因:我在index.jsp中使用了<s:action name="list" />,但是struts文档说如果我们想用<s:action>看到结果页面,那么我们必须将其属性executeResult设置为true,即就像<s:action name="list" executeResult="true"/>。 在我看来,这有点奇怪,这个属性默认应该是 true。 有一个示例,您应该如何使用 Shiro applicationContext.xml 进行配置: <property name="filterChainDefinitions"> <value> # some example chain definitions: /admin/** = authc, roles[admin] /** = authc # more URL-to-FilterChain definitions here </value> </property> 以 /admin/ 开头的 URL 通过角色 admin 进行保护,任何其他 URL 均不受保护。如果 Struts 操作和结果 JSP 不在受保护区域中,则会显示它们。


ng-bootstrap 滚动间谍在没有高度的情况下无法工作?

我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: 我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: <div> <div class="sticky-top"> <ul class="nav menu-sidebar"> <li > <a [ngbScrollSpyItem]="[spy, 'about']">About</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="schedule">Schedule</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="hotel">Information about the hotel</a> </li> </ul> </div> <div ngbScrollSpy #spy="ngbScrollSpy" > <section ngbScrollSpyFragment="about"> <h3>About</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="schedule"> <h3>Schedule</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="hotel"> <h3>Information about the hotel</h3> <p>{{some long long text and content}}</p> </section> </div> </div> 我在这个 stackoverflow 问题中看到,我的问题是我没有向我的 div 提供 height,这是事实。 但我的滚动间谍部分遍布整个页面,而不是一个小 div,(导航本身是 sticky-top)。所以我不能给它高度。 我知道有替代方法 - 刷新窗口滚动上的滚动间谍,但我没有找到可以帮助我的正确代码。 你能解决我的问题吗? 为我提供刷新滚动间谍的代码/给我有关高度的提示/帮助我找到另一个相应的元素。 非常感谢! 附上 stackblitz 演示的链接 注意:我使用来自 @ng-bootstrap/ng-bootstrap 的 NgbScrollSpy (我想它是非常相似的库) 我做什么: 我将所有内容(包括导航)包装在中 <div class="wrapper" ngbScrollSpy #spy="ngbScrollSpy" rootMargin="2px" [threshold]="1.0" > <div class="sticky-top pt-4 pb-4 bg-white"> ..here the navigation... </div> ..here the sections... <section ngbScrollSpyFragment="about"> </section> //the last I use margin-bottom:2rem; <section ngbScrollSpyFragment="hotel" style="margin-bottom:10rem" </section> </div> 见“门槛”。这表明“更改”活动片段应该可见的百分比(1 是 100%) 包装类 .wrapper{ height:100%; position: absolute; top:0; } 我使用强制链接的类别 //remove all the class for the link a{ color:black; text-decoration:none; padding:8px 16px; } a.custom-active{ color:white; background-color:royalblue } 以及我使用的每个链接 <a [class.custom-active]="spy.active=='about'">About</a> 嗯,问题是如何“滚动到”。 “链接”应该作为链接使用。 第一个是指示“路由器”应该考虑“碎片” 如果我们的组件是独立组件,我们需要使用提供者,provideRouter bootstrapApplication(App, { providers: [ provideRouter([], withInMemoryScrolling({anchorScrolling:'enabled'})), ] }) 然后,我们需要考虑到我们的页面确实没有滚动,div“包装器”是谁拥有滚动。因此,我们订阅 router.events,当事件有“锚点”时,我们滚动“包装器”div constructor(router: Router) { router.events.pipe(filter((e:any) => e.anchor)).subscribe((e: any) => { (document.getElementById('wrapper') as any).scrollTop+= (document.getElementById(e.anchor)?.getBoundingClientRect().top||0) -72; //<--this is the offset }); } 在这个stactblitz中你有一个有效的例子


Laravel 路由添加模板名称

我有一个名为 Lodge.upload 的刀片模板。在该模板中,我有以下代码: 我有一个名为 Lodge.upload 的刀片模板。在该模板中,我有以下代码: <form name="app" action="storeSummons" enctype="multipart/form-data" method="post"> 在我的路线文件中我有这个: Route::post('/storeSummons',[\App\Http\Controllers\LodgesController::class,'storeSummons'])->name('storeSummons'); 当我尝试从这个简单的表单(只有两个字段)发布时,我收到错误 Lodge.uploads/storeSummons 路由不支持 POST 方法。支持的方法:GET、HEAD 该路线明确标记为 storeSummons,没有提及模板名称或其路线。 我已经尝试清除缓存、路由、视图,但它仍然坚持将其添加到路由中。该组仅具有添加中间件的身份验证。 这让我发疯,我检查了路线是否被重复但没有成功。 我将协助您解决 Laravel 应用程序中的“不支持 POST 方法”错误。以下是综合的回应,结合了专家反馈的见解并解决了潜在的原因: 理解错误: 不正确的路线或方法:该错误表明两者之间不匹配 表单的提交方法和定义的路线。 缺少 CSRF 令牌:Laravel 需要有效的 CSRF 令牌才能进行 POST 请求以防止跨站点请求伪造攻击。 故障排除步骤: 验证路线定义: 确保路由定义为 POST 路由: Route::post('/storeSummons', ...)。 检查是否有任何具有相同路径或名称的冲突路由。 如果路由在组内,请确认该组的中间件 配置。 包含 CSRF 代币: 在表单中添加 @csrf 指令: <form name="app" action="storeSummons" enctype="multipart/form-data" method="post">@csrf</form> 检查路由缓存: 清除路由缓存:php artisan route:clear。 如果使用缓存机制,也清除那里的缓存。 回顾中间件: 检查应用于路由或组的中间件,确保它们不会干扰 - POST 请求。 检查浏览器开发者工具: 检查网络请求的路径和方法是否正确。 查找任何指示问题的错误或警告。


如何解决数字格式异常?

index.html 输入第一个数字: 输入第二个数字... index.html <!DOCTYPE html> <html> <body> <form action="add"> Enter 1st number:<input type="text" name="num1"><br> Enter 2st number:<input type="text" name="num1"><br> <input type="submit"> </form> </body> </html> AddServlet.java 这是 servlet 代码。 package com.adithya; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AddServlet extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res) throws IOException { int i=Integer.parseInt(req.getParameter("num1")); int j=Integer.parseInt(req.getParameter("num2")); int k=i+j; PrintWriter out=res.getWriter(); out.println("result is"+k); } } 我正在尝试获取结果,但它显示了如下所示的异常。我无法理解例外情况。 ** 例外** 这显示了这样的异常。我无法识别问题所在。 java.lang.NumberFormatException: Cannot parse null string java.base/java.lang.Integer.parseInt(Integer.java:630) java.base/java.lang.Integer.parseInt(Integer.java:786) com.adithya.AddServlet.service(AddServlet.java:19) javax.servlet.http.HttpServlet.service(HttpServlet.java:623) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) 我不明白这是什么错误。我试图从 2 天开始解决这个问题。请任何人帮助我解决这个问题。但它不起作用。 您有 2 个相同的名字 num1,并且您正在尝试呼叫不在场的 num2。 Enter 2st number:<input type="text" name="num1"><br> 关于: Enter 2st number:<input type="text" name="num2"><br>


从数据库中选择 SELECT 选项后如何显示/隐藏 DIV?

这是选择选项的代码; 这是选择选项的代码; <div class="modal-body row"> <form role="form" action="patient/addNew" class="clearfix" method="post" enctype="multipart/form-data"> <div class="form-group col-md-6"> <label for="exampleInputEmail1"><?php echo lang('categorie'); ?></label> <select class="form-control m-bot15" name="categorie" value='' id="p_category"> <option value="#"> Sélectionner catégorie</option> <?php foreach ($categories as $category) { ?> <option value="category"><?php if (!empty($setval)) { if ($category->category == set_value('category')) { echo 'selected'; } } if (!empty($patient->category)) { if ($category->category == $patient->category) { echo 'selected'; } } ?> > <?php echo $category->category; ?> </option> <?php } ?> </select> </div> 这是必须显示/隐藏的 div: <label for="exampleInputEmail1"><?php echo lang('name_Us'); ?></label> <input type="text" class="form-control" name="name_husband" id="nameUs" placeholder=""> <label for="exampleInputEmail1"><?php echo lang('number_pre'); ?></label> <input type="number" class="form-control" name="number_pre" id="nbreEnf" placeholder=""> </div> 这是 JavaScript 代码: $('.divUs').hide(); $(document.body).on('change', '#p_category', function () { var v = $("select.p_category option:selected").val() if (v == 'Fe_Ence') { $('.divUs').show(); } else { $('.divUs').hide(); } }); }); 我希望如果选择了元素(Fe_Ence),则可以显示 div,否则,它保持隐藏 例如,您可以使用 :has 选择器 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="thingtohide"> <h1>Hello</h1> </div> <div id="checkbox"> <input type="checkbox"> </div> <style> body:has(#checkbox input:checked) #thingtohide { visibility: hidden; } </style> </body> </html> 因此,如果父元素有一个选中的复选框,那么您可以定位与该父元素不同的子元素。


IIS Rewrite 在重写到外部网站时始终返回 502 bad gateway

是一个部署在IIS上的小网站。我正在使用此网站上的重写功能来重写对外部网站的 http 请求。这是 web.config 中的重写设置。 是一个部署在IIS上的小网站。我正在使用此网站上的重写功能来重写对外部网站的 http 请求。这是 web.config 中的重写设置。 <system.webServer> <rewrite> <rules> <rule name="ReverseProxyInboundRule1" stopProcessing="true"> <match url="(.*)" /> <action type="Rewrite" url="https://about.gitlab.com/" logRewrittenUrl="true" /> </rule> </rules> </rewrite> </system.webServer> 它总是返回HTTP Error 502.2 - Bad Gateway。 HTTP 错误 502.2 - 网关错误 尝试路由请求时出现连接错误。 如果我只是使用指向此网站内页面的内部路径,使用相对路径,以 / 开头,那么它就可以正常工作。改成外部网站后,总是返回HTTP Error 502.2 - Bad Gateway。 有什么地方需要更新吗? 这是我解决问题的方法。它可能不是所有502 bad gateway问题的解决方案,但它解决了我的问题。 在应用程序请求路由 -> 缓存设置 -> 内存缓存持续时间中。我把他的值设置为0。然后它就按预期工作了。


从数据库表中选择选择选项后如何显示/隐藏隐藏的 Div?

以下是选择选项的代码: 这是选择选项的代码: <div class="modal-body row"> <form role="form" action="patient/addNew" class="clearfix" method="post" enctype="multipart/form-data"> <div class="form-group col-md-6"> <label for="exampleInputEmail1"><?php echo lang('categorie'); ?></label> <select class="form-control m-bot15" name="categorie" value='' id="p_category"> <option value="#"> Sélectionner catégorie</option> <?php foreach ($categories as $category) { ?> <option value="category"><?php if (!empty($setval)) { if ($category->category == set_value('category')) { echo 'selected'; } } if (!empty($patient->category)) { if ($category->category == $patient->category) { echo 'selected'; } } ?> > <?php echo $category->category; ?> </option> <?php } ?> </select> </div> 这是应该显示/隐藏的 Div: <div class="form-group col-md-6" id="divCacher" style="display: none"> <label for="exampleInputEmail1"><?php echo lang('name_husband'); ?></label> <input type="text" class="form-control" name="name_Us" id="nameUs" placeholder=""> <label for="exampleInputEmail1"><?php echo lang('number_pregnancy'); ?></label> <input type="number" class="form-control" name="number_pregnancy" id="nbreEnfants" placeholder=""> </div> 这是 JavaScript 代码: $(document).ready(function () { $('.divCacher').hide(); $(document.body).on('change', '#p_category', function () { var v = $("select.p_category option:selected").val() if (v == 'Fe_Ence') { $('.divCacher').show(); } else { $('.divCacher').hide(); } }); }); 我希望如果我们选择 Fe_Ence 类别,则 div 会显示,否则,它会保持隐藏 您需要将 $category 设置为选项值更改此: <option value="category"> 对此: <option value="<?=$category?>"> 以下是适用于更多此类情况的示例: <!--SELECT INPUT--> <select id="p_category"> <option value=""> Sélectionner catégorie</option> <?php foreach ($categories as $category): ?> <option value="<?=$category?>"><?=$category?> <?php endforeach;?> </select> <!--Container List--> <div class="cat-container" data-id="test1"> <h1>This is Test1 Category</h1> </div> <div class="cat-container" data-id="Fe_Ence"> <h1>This is Fe_Ence Category</h1> </div> <div class="cat-container" data-id="test3"> <h1>This is test3 Category</h1> </div> // Javascript code checkCategory(); $("#p_category").on('change', checkCategory) function checkCategory() { $('.cat-container').hide() const selected = $('#p_category').val() if (!selected) return; $(`[data-id=${selected}`).show() }


ML.net - CreateTimeSeriesEngine

我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 列表 我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 List<RateData> infoList = new List<RateData>(); // populate list infoList = FileParser(infoList); IDataView data = mlContext.Data.LoadFromEnumerable<RateData>(infoList); 我设法像这样运行预测估计器 var forecastEstimator = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatePrediction.CurrentRate), inputColumnName: nameof(RateData.HistoricalRate), windowSize: 14, seriesLength: numRateDataPoints, trainSize: numRateDataPoints, horizon: 1, confidenceLevel: 0.95f ); SsaForecastingTransformer forecaster = forecastEstimator.Fit(RateDataSeries); 然后我尝试创建这样的预测引擎 var ForecastEngine = Forecaster.CreateTimeSeriesEngine(mlContext); 这里我遇到了一些错误。 我的输入和输出类如下: public class RateData { public DateTime TransactionDate { get; set; } public float HistoricalRate { get; set; } } public class RatePrediction { public float CurrentRate; } 我有这样的错误 System.InvalidOperationException: Can't bind the IDataView column 'CurrentRate' of type 'Vector<Single, 1>' to field or property 'CurrentRate' of type 'System.Single'. at Microsoft.ML.Data.TypedCursorable`1..ctor(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, InternalSchemaDefinition schemaDefn) at Microsoft.ML.Data.TypedCursorable`1.Create(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, SchemaDefinition schemaDefinition) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2.PredictionEngineCore(IHostEnvironment env, InputRow`1 inputRow, IRowToRowMapper mapper, Boolean ignoreMissingColumns, SchemaDefinition outputSchemaDefinition, Action& disposer, IRowReadableAs`1& outputRow) at Microsoft.ML.PredictionEngineBase`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition, Boolean ownsTransformer) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at Microsoft.ML.Transforms.TimeSeries.PredictionFunctionExtensions.CreateTimeSeriesEngine[TSrc,TDst](ITransformer transformer, IHostEnvironment env, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at USD_EURO_Conversion_rate.TimeSeriesModelHelper.FitAndSaveModel(MLContext mlContext, IDataView RateDataSeries, String outputModelPath) 预测类中的属性需要是float[]类型;向量/数组而不是单个值,例如 public class RatePrediction { public float[] CurrentRate; } 类似于此处的Microsoft 示例。


如何在node js中使用DOM更改文本内容

我想做的是 我想在输入错误密码时将标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 我想做的是 我想在输入错误密码时将 标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 <form action="/check" method="POST"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> 这是我的 javascript 文件内容 import express from "express"; import {dirname} from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const pass = "ILoveProgramming"; var enter = ""; app.use(bodyParser.urlencoded({extended:true})); function checker(req, res, next){ enter = req.body.password; console.log(enter); next(); } app.use(checker); app.get("/", (req,res) =>{ res.sendFile(__dirname +"/public/index.html"); }); app.post("/check",(req,res)=>{ if(pass === enter){ res.sendFile(__dirname+"/public/secret.html"); } else{ document.querySelector("p").textContent("The paswrd is wrong"); console.log("The password is incorrect"); } // console.log(enter); }); app.use(bodyParser); app.listen(port, () =>{ console.log(`server is live at ${port}`); }); 我对这一切都是新手所以把我当作一个没有任何经验的人 document对象是浏览器DOM API的一部分,它在服务器端不可用。在浏览器控制台上,它是 window 对象的属性。 window.document。 您正在尝试操作服务器上的 DOM,这是不可能的。您应该在浏览器接收并呈现 HTML 页面后在客户端处理 DOM 操作。为此,您应该在 HTML 文件内有一个 script 标签。 <script> // inside here you add your logic to access document <script/> script标签将在浏览器上执行,您可以访问此标签内的document对象


活动深层链接 - IllegalArgumentException:缺少必需的参数并且没有 android:defaultValue

在我的应用程序中,我有以下结构: 在我的应用程序中,我具有以下结构: <!-- AndroidManifest.xml --> <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <activity android:name=".DeepLinkActivity" android:exported="true" android:launchMode="singleInstancePerTask"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="myhost" android:path="/mypath" android:scheme="myscheme" /> </intent-filter> </activity> </application> </manifest> <!-- activity_deep_link.xml --> <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.fragment.app.FragmentContainerView android:id="@+id/navHostFragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" tools:navGraph="@navigation/my_nav_graph" /> </FrameLayout> // DeepLinkActivity.kt class DeepLinkActivity : AppCompatActivity() { private lateinit var binding: ActivityDeepLinkBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDeepLinkBinding.inflate(layoutInflater) setContentView(binding.root) setUpNavigationGraph() } private fun setUpNavigationGraph() { val navHostFragment = supportFragmentManager .findFragmentById(binding.navHostFragment.id) as NavHostFragment val navController = navHostFragment.navController val navGraph = navController.navInflater .inflate(R.navigation.my_nav_graph) .apply { this.setStartDestination(R.id.notTheStartDestinationFragment) } val startDestinationArgs = bundleOf( "someRequiredArgumentHere" to false ) navController.setGraph(navGraph, startDestinationArgs) } } 当我通过 ADB (adb shell am start -d myscheme://myhost/mypath) 通过深度链接打开该活动时,该活动正常启动。 但是当我通过 Chrome 应用程序启动它时,应用程序崩溃了: 原因:java.lang.IllegalArgumentException:缺少必需参数“someRequiredArgumentHere”并且没有 android:defaultValue 观察:我正在使用 Safe Args 插件。 我做错了什么以及为什么行为不同? 我刚刚发现为什么在通过浏览器导航时会忽略 startDestinationArgs。 如果我们检查NavController#setGraph(NavGraph, Bundle?)的内部代码,如果没有发生深层链接,NavController#onGraphCreated(Bundle?)只会使用startDestinationArgs。 作为一种解决方法,在设置导航图之前,我只需清除活动的意图(但这可能不是解决该问题的最佳方法)


替换字符串后在 echo 中运行额外的 php 代码

我想在替换表单中的一些字符串后执行附加的php代码 这是我在 form.php 上的表单代码 我想在替换表单中的一些字符串后执行附加的php代码 这里是我在 form.php 上的表单代码 <form method="post" action="result.php"> <input type="text" name="yourtext"> <input type="submit"> </form> 例如文本是 my name is bagu and i live under a rock thanks 这里是 result.php 代码 <?php $mytext = $_POST['yourtext']; $find = ["my name is","and i live", "thanks"]; $replace = ["<?php open_form('Form/insert') ?><input name='name' type='text' value='","'><br><input name='address' type='text' value='","'><input type='submit'><?php form_close() ?>"]; $intoform = str_replace($find, $replace, $mytext); echo $intoform; ?> 我想要的结果是“bagu”和“under a rock”分别在一个正在工作的文本框中 但问题是 echo 中的 php 代码不起作用(我认为???因为它是) 是的,这是 codeigniter 的表格 谢谢 ====== 编辑:我尝试了没有 echo 和变量的 result.php ,也就是我在 form.php 中提交文本后想要的结果 <?php open_form('Form/insert') ?> <input name='name' type='text' value='bagu'><br> <input name='address' type='text' value='under a rock'> <input type='submit'> <?php form_close() ?> 并且如果“ 使用 preg_match 提取姓名和地址。 die 子句仅用于指示输入字符串格式错误,可以根据需要替换为更友好的提示。 preg_match('/my name is (.+) and i live (.+) thanks/', $mytext, $m) or die('Input text is invalid'); 如果preg_match成功,$m[1]将包含名称,$m[2]将包含地址,然后您可以将值插入表单 <?php open_form('Form/insert') ?> <input name='name' type='text' value='<?=$m[1]?>'><br> <input name='address' type='text' value='<?=$m[2]?>'> <input type='submit'> <?php form_close() ?> 需要补充的是,在实际操作中,应检查用户输入的姓名和地址的合法性。例如,要限制它们仅包含字母和空格,第一步中的正则表达式 (.+) 可以更改为 ([A-Za-z ]+)。


具有多个值的JS var

有件事我无法理解: 我有一个打开同一页面的功能,但具有不同的内容,具体取决于菜单中单击的按钮: 有件事我无法理解: 我有一个打开同一页面的功能<div id="page">但具有不同的内容,具体取决于菜单中单击的按钮: <nav> <button onclick="openPage(1)">PAGE 1</button> <button onclick="openPage(2)">PAGE 2</button> <button onclick="openPage(3)">PAGE 3</button> </nav> 然后是函数: function openPage(p){ var move=0; // define a var for USER action if(p==1){ document.getElementById('page').innerHTML = text_1; // content preloaded } else if(p==2){ document.getElementById('page').innerHTML = text_2; } else if(p==3){ document.getElementById('page').innerHTML = text_3; } // then on the top of the page (absolute + z-index) I add a HTML object: document.getElementById('page').innerHTML += '<aside id="pictures">content</aside>'; // what I'm now trying to do is to remove this object once USER move its mouse on it document.getElementById('pictures').addEventListener("mousemove",function(event) { setTimeout(function(){ move+=1; // increase the val each second },1e3) console.log('move'+p+' = '+move) // control value if(move>100){ document.getElementById('pictures').style.display = "none"; // OK, it works move=0; // reinit the var } }); } 现在惊喜: 第 1 页的控制台 move1 = 0 move1 = 1 ... move1 = 99 move1 = 100 // 'pictures' disappears 第 2 页的控制台 move1 = 41 move2 = 0 ... move1 = 58 move1 = 17 ... move1 = 100 // 'pictures' disappears move2 = 59 第 3 页的控制台 move1 = 15 move2 = 88 move3 = 0 ... move1 = 37 move2 = 100 // 'pictures' disappears move3 = 12 ... 我的 var 'move' 同时获得 3 个值...这怎么可能? 您的问题的原因是您每次调用 openPage 函数时都会添加一个事件侦听器。这意味着,如果您单击多个按钮,每个按钮都会有自己的事件侦听器附加到 #pictures 元素。现在,当触发 mousemove 事件时,所有这些侦听器将同时执行,导致 move 变量每秒递增多次。 解决此问题的方法是在添加新事件侦听器之前先删除现有的事件侦听器。 let handler; // to hold the event listener function const pictureEl = document.getElementById('pictures'); function openPage(p){ // Remove existing event listener if (handler) { // <-- Check here pictureEl.removeEventListener("mousemove", handler); } handler = function(event) { // ...Rest } }; // Add new event listener pictureEl.addEventListener("mousemove", handler); // ...rest 找到了另一种(最简单的?)方法: var move=0; // placed out of functions function openPage(p){ .... (same as previous) getElementById('pictures').addEventListener("mousemove",outPicts); // change } // put mousemove event in another function: function outPicts(p){ setTimeout(function(){ move+=1; },1e3) console.log('move = '+move) if(move>100){ document.getElementById('pictures').style.display = "none"; // then remove event getElementById('pictures').removeEventListener("mousemove",outPicts); move=0; // reinit the var } } 按预期工作


jQuery Ajax 在 php 同一页面上传递值 - 更新

如何找回: 如何找回: <div id="test"> <?php if (isset($_POST['sweets'])) { ob_clean(); echo $_POST['sweets']; exit; } ?> </div> <form id="a" action="" method="post"> <select name="sweets" onchange="change()" id="select1"> <option >Chocolate</option> <option selected="selected">Candy</option> <option >Taffy</option> <option >Caramel</option> <option >Fudge</option> <option >Cookie</option> </select> </form> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> function change() { var sweets = $("#select1").val(); $.ajax({ type: "POST", data: { sweets: sweets }, success: function(data) { $("#test").html(data); } }); } </script> 将值传递给 php 字符串: $string = $_POST['sweets']; <!-- I'm looking for this: --> 我希望这是可能的。我在 stackoverflow 和 google 上寻找答案,但找不到适合我的目的的答案。 对于同一个页面的ajax/PHP脚本,可以将PHP放在脚本的最前面,当有POST提交数据时以exit结束 为了使其更有意义,您应该返回与您通过 POST 提交的内容相关的内容(这是甜食的类型),作为示例,我们展示其一般定义。我们可以使用 switch,这是用于此目的的常用结构: switch ($string) { case "Chocolate": echo "Chocolate is made from cocoa beans, the dried and fermented seeds of the cacao tree"; break; case "Candy": echo "Candy is a sweet food made from sugar or chocolate, or a piece of this"; break; case "Taffy": echo "Taffy is a type of candy invented in the United States, made by stretching and/or pulling a sticky mass of a soft candy base"; break; case "Caramel": echo "Caramel is made of sugar or syrup heated until it turns brown, used as a flavouring or colouring for food or drink"; break; case "Fudge": echo "Fudge is a dense, rich confection typically made with sugar, milk or cream, butter and chocolate or other flavorings"; break; case "Cookie": echo "A cookie (American English) or biscuit (British English) is a baked snack or dessert that is typically small, flat, and sweet"; break; } exit; } ?> 所以以下是示例代码: <?php if (isset($_POST['sweets'])) { // ob_clean(); $string = $_POST['sweets']; switch ($string) { case "Chocolate": echo "Chocolate is made from cocoa beans, the dried and fermented seeds of the cacao tree"; break; case "Candy": echo "Candy is a sweet food made from sugar or chocolate, or a piece of this"; break; case "Taffy": echo "Taffy is a type of candy invented in the United States, made by stretching and/or pulling a sticky mass of a soft candy base"; break; case "Caramel": echo "Caramel is made of sugar or syrup heated until it turns brown, used as a flavouring or colouring for food or drink"; break; case "Fudge": echo "Fudge is a dense, rich confection typically made with sugar, milk or cream, butter and chocolate or other flavorings"; break; case "Cookie": echo "A cookie (American English) or biscuit (British English) is a baked snack or dessert that is typically small, flat, and sweet"; break; } exit; } ?> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select name="sweets" onchange="change()" id="select1"> <option value="">Please select</option> <option >Chocolate</option> <option >Candy</option> <option >Taffy</option> <option >Caramel</option> <option >Fudge</option> <option >Cookie</option> </select> <br><br> <div id="test"></div> <script> function change() { var sweets = $("#select1").val(); $.ajax({ type: "POST", data: { sweets: sweets }, success: function(data) { $("#test").html(data); } }); } </script>


php 中的用户欢迎消息

如何在 php.ini 中创建用户欢迎消息这样已经登录的用户就能够看到他的用户名。 我有这段代码,但它似乎不起作用。 如何在 php.ini 中创建用户欢迎消息这样已经登录的用户就能够看到他的用户名。 我有这个代码,但它似乎不起作用。 <?php $con = mysql_connect("localhost","root","nitoryolai123$%^"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("school", $con); $result = mysql_query("SELECT * FROM users WHERE Username='$username'"); while($row = mysql_fetch_array($result)) { echo $row['Username']; echo "<br />"; } ?> 我正在尝试利用在此登录表单中输入的数据: <form name="form1" method="post" action="verifylogin.php"> <td> <table border="0" cellpadding="3" cellspacing="1" bgcolor=""> <tr> <td colspan="16" height="25" style="background:#5C915C; color:white; border:white 1px solid; text-align: left"><strong><font size="2">Login User</strong></td> </tr> <tr> <td width="30" height="35"><font size="2">Username:</td> <td width="30"><input name="myusername" type="text" id="idnum" maxlength="5"></td> </tr> <tr> <td width="30" height="35" ><font size="2">Password:</td> <td width="30"><input name="mypassword" type="password" id="lname" maxlength="15"></td> </tr> <td align="right" width="30"><td align="right" width="30"><input type="submit" name="Submit" value="Submit" /></td> <td align="right" width="30"><input type="reset" name="Reset" value="Reset"></td></td> </tr> </form> 但是这个 verifylogin.php 似乎很碍事。 <?php $host="localhost"; $username="root"; $password="nitoryolai123$%^"; $db_name="school"; $tbl_name="users"; mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("myusername"); session_register("mypassword"); header("location:userpage.php"); } else { echo "Wrong Username or Password"; } ?> 我该怎么做?当我运行它时,我总是收到此错误: Notice: Undefined variable: username in C:\wamp\www\exp\userpage.php on line 53 您能推荐一个更简单的方法来实现同样的目标吗? $result = mysql_query("SELECT * FROM users WHERE Username='$username'"); 你忘记从某处定义和填充$username 您还需要添加 exit();在以下代码之后: session_register("myusername"); session_register("mypassword"); header("location:userpage.php"); exit(); ## EXIT REQUIRED 如果您不添加此内容并且客户端刷新,则会提示“您确定要重新提交已发布的变量吗?”如果他们单击“是”,那么您所有的登录逻辑将再次执行。在这种情况下,这可能不是致命的事情,但无论如何你都应该拥有它。 最重要的是:如果新用户登录,需要显示不同的名称,而不是显示以前的名称


表单响应:“无法处理请求 HTTP ERROR 500”。我做错了什么?

我尝试在网站上编写 php 表单,但收到错误 500。我无法弄清楚我做错了什么。你能看一下代码看看我做错了什么吗? PHP: 我尝试在网站上编写 php 表单,但收到错误 500。我无法弄清楚我做错了什么。你能看一下代码看看我做错了什么吗? PHP: <?php // define variables and set to empty values $name = $email = $phone = $enquiry = ""; if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) { if ( empty( $_POST[ "name" ] ) ) { $nameErr = "Name is required"; } else { $name = test_input( $_POST[ "name" ] ); // check if name only contains letters and whitespace if ( !preg_match( "/^[a-zA-Z-' ]*$/", $name ) ) { $nameErr = "Only letters and white space allowed"; } } if ( empty( $_POST[ "email" ] ) ) { $emailErr = "Email is required"; } else { $email = test_input( $_POST[ "email" ] ); // check if e-mail address is well-formed if ( !filter_var( $email, FILTER_VALIDATE_EMAIL ) ) { $emailErr = "Invalid email format"; } } if ( empty( $_POST[ "phone" ] ) ) { $comment = ""; } else { $comment = test_input( $_POST[ "phone" ] ); } if ( empty( $_POST[ "enquiry" ] ) ) { $comment = ""; } else { $comment = test_input( $_POST[ "enquiry" ] ); } } // Create the email and send the message $destination = "[email protected]"; $subject = "Website Contact Form Enquiry: $name"; $body = "You have received a new message from your website contact form.\\n\\n"."Here are the details:\\n\\nName: $name\\n\\nEmail: $email\\n\\nPhone: $phone\\n\\nEnquiry:\\n$enquiry"; $header = "From: [email protected]\\n"; $headers = array(); $headers[] = "MIME-Version: 1.0"; $headers[] = "Content-type: text/plain; charset=iso-8859-1"; $headers[] = "From: " . $fromAddress; $headers[] = "Subject: " . $subject; $headers[] = "X-Mailer: PHP/".phpversion(); mail($destination, $subject, $message, implode("\r\n", $headers)); // mail($to,$subject,$msg,$headers); echo "Email successfully sent."; ?> HTML 格式: <form id="contact-form" method="post" action="/contact.php" role="form"> <div class="messages"></div> <div class="controls"> <div class="row"> <div class="col-md-10"> <div class="form-group"> <input id="form_name" type="text" name="name" class="form-control" placeholder="Name*" required="required" data-error="Your name is required." > <div class="help-block with-errors"></div> </div> </div> <div class="col-md-10"> <div class="form-group"> <input id="form_email" type="email" name="email" class="form-control" placeholder="Email*" required="required" data-error="Valid email is required." > <div class="help-block with-errors"></div> </div> </div> <div class="col-md-10"> <div class="form-group"> <input id="form_phone" type="text" name="phone" class="form-control" placeholder="Phone" > <div class="help-block with-errors"></div> </div> </div> </div> <div class="row"> <div class="col-md-10"> <div class="form-group"> <textarea id="form_enquiry" name="enquiry" class="form-control" placeholder="Enquiry*" rows="6" required="required" data-error="Please, leave us a message."></textarea> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-12"> <input class="btn btn-large btn-primary centre mt-10" type="submit" value="Submit" > </div> </div> </div> </form> 我已按照其他人的指示使表单正常工作,但所做的更改仍然会出现错误。 这是一个简单的形式,但我似乎对我做错了什么缺乏了解。 请帮助我。 如果您查看发送邮件的行,这是一个硬行结尾,将 $headers 推到新行上吗?这将调用 500 错误。 查看 /var/log/apache2/error.log(如果您使用的是 Debian)或 /var/log/httpd/error.log(如果使用的是 RHEL 或类似系统)。 您的代码存在许多问题,但首先关注快乐的道路,然后让事情正常运行。


你能用最简单的方法告诉我使用jquery上传文件吗?

我想使用最简单的方法通过jquery ajax上传文件。 我的代码是: ... 我想用最简单的方法通过jquery ajax上传文件。 我的代码是: <body> <form action="?" method="POST" enctype="multipart/form-data"> <input type="file" name="myfile" /><br> <input type="submit" name="submit_btn" value="Submit" /> </form> <div> <?php if (isset($_POST['submit'])) { //move_uploaded_files()... } ?> </div> </body> 当您使用网页上的表单向服务器发送数据时,您可以选择使用 GET 或 POST 方法。这些方法决定了数据如何发送到服务器。 当您将表单方法设置为 GET 时,您在表单字段中填写的数据(包括您选择的文件)会以某种方式添加到网址中。您可能已经注意到,当您提交表单时,浏览器中的 URL 会发生变化。然而,这种方法有一些局限性。它不适合发送大块数据(例如文件),并且以这种方式发送的数据量有最大限制。 另一方面,当您使用 POST 方法时,您输入表单的数据会以不同的方式发送,有点像后台的隐藏包。它更适合包含文件在内的大量数据。这就是当您将表单方法更改为 POST 时文件上传有效的原因。服务器知道如何处理此类数据并正确存储它。 在您的具体情况下,当您将表单方法更改为 GET 时,$_FILES 数组无法按预期工作,因为它旨在处理使用 POST 方法发送的数据。这有点像试图在方孔中安装圆钉 - GET 方法并非旨在像 POST 那样处理文件上传。 如果你确实需要使用GET方法并且仍然想上传文件,那就有点棘手了。您可能需要发挥创意,以可添加到 URL 的方式对文件数据进行编码,但由于各种问题,这并不是处理文件的最佳方式。 一般来说,对于文件上传,使用POST方法会更好。它确保您的文件安全地到达服务器,并避免尝试将像文件这样的大东西放入像 URL 这样的小空间中的复杂性。如果您决定使用 GET,您可能需要考虑不同的方法来实现您的目标,例如将文件临时存储在服务器上并通过 URL 传递对这些文件的引用。 那是因为 GET 请求没有正文,而这就是文件所在的位置


如何使用javascript forloop在点击时获取html中data-id的值并返回值

这是我的html {% if t_ques %} 今天 {% 表示 t_... 中的项目 这是我的html <ul class="conversations"> {% if t_ques %} <li class="grouping">Today</li> {% for item in t_ques %} <li class="active"> <a id="convers" class="conversation-button text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}"> <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }} </a> <div class="fade"></div> <div class="edit-buttons"> <button><i class="fa fa-edit"></i></button> <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button> </div> </li> {% endfor %} {% endif %} {% if y_ques %} <li class="grouping">Yesterday</li> {% for item in y_ques %} <li> <a id="convers" class="conversation-button text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}"> <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }} </a> <div class="fade"></div> <div class="edit-buttons"> <button><i class="fa fa-edit"></i></button> <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button> </div> </li> {% endfor %} {% endif %} {% if s_ques %} <li class="grouping">Previous 7 days</li> {% for item in s_ques %} <li> <a id="convers" class="conversation-button text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}"> <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }} </a> <div class="fade"></div> <div class="edit-buttons"> <button><i class="fa fa-edit"></i></button> <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button> </div> </li> {% endfor %} {% endif %} {% if more_s_ques %} <li class="grouping">Previous 30 days</li> {% for item in more_s_ques %} <li> <a id="convers" class="conversation-button text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}"> <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }} </a> <div class="fade"></div> <div class="edit-buttons"> <button><i class="fa fa-edit"></i></button> <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button> </div> </li> {% endfor %} {% endif %} </ul> </div> 我一直在尝试使用 JavaScript 单击时获取任何 data-pk 的值,但似乎无法实现。这一直说 currentTarget 未定义,当我用 target 替换它时,它说同样的事情。然后,如果我将其替换为 document.querySelector("#convers"),它只会给出第一个值,无论单击哪个 这是我的 JavaScript const conversationButtons = document.querySelectorAll("#convers"); conversationButtons.forEach(button => { button.addEventListener("click", getId); }); function getId(e){ var idValue = e.currentTarget.getAttribute('data-pk'); console.log(idValue); //output corresponding target-id if(!chat_id){ url = `/chat-previous/${idValue}/` }else{ url = 'initiate-chat/' } return url; } $.ajax({ type: 'POST', url: getId(), data: { message: usermsg, chatId: chat_id, // itemId: item_id, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function(json){ const res = json['chats'] setTimeout(() => { hideTyping(); body.appendChild(mgses(res, "assistant")); scrollToBottomOfResults(); }, 1000); console.log(json) }, error: function(rs, e){ setTimeout(() => { hideTyping(); body.appendChild(setBotResponse("bot")); scrollToBottomOfResults(); }, 600); console.log(rs.error); }, }); 我使用了其他方法,例如 const getId = () => { console.log(document.querySelector(".conversation-button").getAttribute('data-pk')) if(!chat_id){ url = `/chat-previous/${document.querySelector(".conversation-button").getAttribute('data-pk')}/` }else{ url = 'initiate-chat/' } return url; } conversationButtons.forEach(button => { button.addEventListener("click", getId); console.log(button.getAttribute('data-pk')); }); 仍然无法得到我真正想要的。有什么方法可以实现这个目标吗? 委托并使用按钮的类 document.querySelector('.conversations').addEventListener('click', (e) => { let tgt = e.target.closest('.conversation-button'); if (!tgt) return; const idValue = tgt.dataset.pk; console.log(idValue); //output corresponding target-id return chat_id ? 'initiate-chat/' : `/chat-previous/${idValue}/` }) 您做出了多个错误的假设,第一个是您不能有多个具有相同 id 的元素,这将导致您描述的确切行为“它需要第一次出现的 id” 第二件事是你可能想在点击时发出ajax请求,但你构建代码的方式并不能做到这一点。 要解决这些问题,请生成如下 html button.conversation-button button.conversation-button button.conversation-button 然后向所有具有 .conversation-button 类的元素添加一个事件侦听器,并将您的 ajax 调用包装到一个函数中,主要是您已经拥有的函数。 const conversationButtons = document.querySelectorAll(".conversation-button"); conversationButtons.forEach(button => { button.addEventListener("click", doStuff); }); ... function doStuff(e) { $.ajax( ... url: getId(e) ... } function getId(e) { let idValue = e.currentTarget.getAttribute('data-pk'); let url = ...; ... return url; // } 只是一些伪代码让你得到一个想法,祝你好运:)


在 C# 中将 Task<T> 转换为 Task<object>,无需 T

我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: 公共静态类 MyContextExtensions{ 公共静态异步任务 我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: public static class MyContextExtensions{ public static async Task<bool> SomeFunction(this DbContext myContext){ bool output = false; //...doing stuff with myContext return output; } public static async Task<List<string>> SomeOtherFunction(this DbContext myContext){ List<string> output = new List<string>(); //...doing stuff with myContext return output; } } 我的目标是能够从另一个类中的单个方法调用这些方法中的任何一个,并将其结果作为对象返回。它看起来像这样: public class MyHub: Hub{ public async Task<object> InvokeContextExtension(string methodName){ using(var context = new DbContext()){ //This fails because of invalid cast return await (Task<object>)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); } } } 问题是转换失败。我的困境是我无法将任何类型参数传递给“InvokeContextExtension”方法,因为它是 SignalR 中心的一部分并且由 javascript 调用。在某种程度上,我不关心扩展方法的返回类型,因为它只会序列化为 JSON 并发送回 javascript 客户端。但是,我确实必须将 Invoke 返回的值转换为任务才能使用等待运算符。我必须为该“任务”提供一个通用参数,否则它将把返回类型视为 void。因此,这一切都归结为如何成功地将具有通用参数 T 的任务转换为具有对象通用参数的任务,其中 T 表示扩展方法的输出。 您可以分两步完成 - await使用基类执行任务,然后使用反射或dynamic收获结果: using(var context = new DbContext()) { // Get the task Task task = (Task)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); // Make sure it runs to completion await task.ConfigureAwait(false); // Harvest the result return (object)((dynamic)task).Result; } 这是一个完整的运行示例,它将上述通过反射调用 Task 的技术置于上下文中: class MainClass { public static void Main(string[] args) { var t1 = Task.Run(async () => Console.WriteLine(await Bar("Foo1"))); var t2 = Task.Run(async () => Console.WriteLine(await Bar("Foo2"))); Task.WaitAll(t1, t2); } public static async Task<object> Bar(string name) { Task t = (Task)typeof(MainClass).GetMethod(name).Invoke(null, new object[] { "bar" }); await t.ConfigureAwait(false); return (object)((dynamic)t).Result; } public static Task<string> Foo1(string s) { return Task.FromResult("hello"); } public static Task<bool> Foo2(string s) { return Task.FromResult(true); } } 一般来说,要将 Task<T> 转换为 Task<object>,我会简单地采用简单的连续映射: Task<T> yourTaskT; // .... Task<object> yourTaskObject = yourTaskT.ContinueWith(t => (object) t.Result); (文档链接在这里) 但是,您实际的具体需求是 通过反射调用 Task 并获取其(未知类型)结果 。 为此,您可以参考完整的dasblinkenlight的答案,它应该适合您的具体问题。 我想提供一个实现,恕我直言,这是早期答案的最佳组合: 精确的参数处理 无动态调度 通用扩展方法 给你: /// <summary> /// Casts a <see cref="Task"/> to a <see cref="Task{TResult}"/>. /// This method will throw an <see cref="InvalidCastException"/> if the specified task /// returns a value which is not identity-convertible to <typeparamref name="T"/>. /// </summary> public static async Task<T> Cast<T>(this Task task) { if (task == null) throw new ArgumentNullException(nameof(task)); if (!task.GetType().IsGenericType || task.GetType().GetGenericTypeDefinition() != typeof(Task<>)) throw new ArgumentException("An argument of type 'System.Threading.Tasks.Task`1' was expected"); await task.ConfigureAwait(false); object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task); return (T)result; } 您不能将 Task<T> 转换为 Task<object>,因为 Task<T> 不是协变的(也不是逆变的)。最简单的解决方案是使用更多反射: var task = (Task) mi.Invoke (obj, null) ; var result = task.GetType ().GetProperty ("Result").GetValue (task) ; 这很慢且效率低下,但如果不经常执行此代码则可用。顺便说一句,如果您要阻塞等待其结果,那么异步 MakeMyClass1 方法有什么用呢? 另一种可能性是为此目的编写一个扩展方法: public static Task<object> Convert<T>(this Task<T> task) { TaskCompletionSource<object> res = new TaskCompletionSource<object>(); return task.ContinueWith(t => { if (t.IsCanceled) { res.TrySetCanceled(); } else if (t.IsFaulted) { res.TrySetException(t.Exception); } else { res.TrySetResult(t.Result); } return res.Task; } , TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } 它是非阻塞解决方案,将保留任务的原始状态/异常。 最有效的方法是自定义等待者: struct TaskCast<TSource, TDestination> where TSource : TDestination { readonly Task<TSource> task; public TaskCast(Task<TSource> task) { this.task = task; } public Awaiter GetAwaiter() => new Awaiter(task); public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion { System.Runtime.CompilerServices.TaskAwaiter<TSource> awaiter; public Awaiter(Task<TSource> task) { awaiter = task.GetAwaiter(); } public bool IsCompleted => awaiter.IsCompleted; public TDestination GetResult() => awaiter.GetResult(); public void OnCompleted(Action continuation) => awaiter.OnCompleted(continuation); } } 具有以下用法: Task<...> someTask = ...; await TaskCast<..., object>(someTask); 这种方法的局限性在于结果不是 Task<object> 而是一个可等待的对象。 我根据dasblinkenlight的回答做了一个小小的扩展方法: public static class TaskExtension { public async static Task<T> Cast<T>(this Task task) { if (!task.GetType().IsGenericType) throw new InvalidOperationException(); await task.ConfigureAwait(false); // Harvest the result. Ugly but works return (T)((dynamic)task).Result; } } 用途: Task<Foo> task = ... Task<object> = task.Cast<object>(); 这样您就可以将 T 中的 Task<T> 更改为您想要的任何内容。 对于最佳方法,不使用反射和动态丑陋语法,也不传递泛型类型。我将使用两种扩展方法来实现这个目标。 public static async Task<object> CastToObject<T>([NotNull] this Task<T> task) { return await task.ConfigureAwait(false); } public static async Task<TResult> Cast<TResult>([NotNull] this Task<object> task) { return (TResult) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.CastToObject().Cast<T2>(); 这是我的第二种方法,但不推荐: public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, TResult dummy = default) { return (TResult)(object) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.Cast((T2) default); // Or Task<T2> task2 = task.Cast<T1, T2>(); 这是我的第三种方法,但是不推荐:(类似于第二种) public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, Type<TResult> type = null) { return (TResult)(object) await task.ConfigureAwait(false); } // Dummy type class public class Type<T> { } public static class TypeExtension { public static Type<T> ToGeneric<T>(this T source) { return new Type<T>(); } } 用途: Task<T1> task ... Task<T2> task2 = task.Cast(typeof(T2).ToGeneric()); // Or Task<T2> task2 = task.Cast<T1, T2>(); 将 await 与动态/反射调用混合使用并不是一个好主意,因为 await 是一条编译器指令,它会围绕调用的方法生成大量代码,并且使用更多反射来“模拟”编译器工作并没有真正的意义,延续、包装等 因为您需要的是在运行时管理代码,然后忘记在编译时工作的 asyc await 语法糖。重写 SomeFunction 和 SomeOtherFunction 而不使用它们,并在运行时创建的您自己的任务中开始操作。您将得到相同的行为,但代码非常清晰。


© www.soinside.com 2019 - 2024. All rights reserved.