virtual-method 相关问题


以 11 岁孩子的身份解释一下我 - C++ 中的函数指针

请解释一下为什么我应该使用它,当它可能有用时? 当我将它赋予其他函数的参数时,我理解将其用作回调函数,但是有一个关键字“virtual&...


任何人都可以帮助我避免在应用程序上使用模拟位置时被检测到吗,我已经反编译并粘贴了其中的代码,smali 文件

.第 1854 行 invoke-virtual {p1}, Landroid/location/Location;->isFromMockProvider()Z 移动结果 p1 转到:goto_6 .1856号线 :条件_d iget-object p1、p0、Lcom/bel/HYS/FileexplorerActivity$


pandas 系列替换为回填替代品

pandas.Series.replace 的文档包含一个示例: >> 将 pandas 导入为 pd >> s = pd.Series([1, 2, 3, 4, 5]) >> s.replace([1, 2], method='bfill') 0 3 1 3 2 3 ...


这两种转换方式有什么区别?

我有以下代码(从浮点数转换为十六进制数): 浮点数小数 = 12.1; int num = (int) 小数; // <- (Method 1) int num2 = (*(int*) &decimal); // <- (M...


指向 std::vector 的指针作为输出参数

我将一个指向向量的指针作为函数中的输出参数,我不知道这是否是最佳实践: 状态接口::method(const std::vector** outVec); 我正在写...


自定义 Weblogic HTTP 扩展日志记录格式

当前在我的 weblogic 服务器中我已启用 HTTP 日志记录。以下是当前配置。 格式为“扩展”。 扩展日志格式字段为“日期时间 cs-method cs-uri sc-status time...


用 Ruby 编写一个脚本,将所有 *.htm 文件重命名为 *.html

我需要用 Ruby 编写一个脚本,将给定的所有 *.htm 文件重命名为 *.html 目录。 我收到的剧本有一些缺失。 我需要使用适当的方法名称“METHOD”...


主窗口后面出现应用内购买弹出窗口 - Flutter Win32 C++ 应用程序

我正在使用 Flutter Method Channel 开发 Windows 桌面应用程序,并且遇到了应用内购买功能的问题。触发后,购买模式对话框出现在主应用程序后面


使用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 部分


使用 Javascript 更改 HTML 中的文本

如何用 Javascript 替换 HTML 中的文本? 在下面的代码片段中,我需要将文本“作者说”替换为“关于作者”。 谢谢你! 如何用 Javascript 替换 HTML 中的文本? 在下面的代码片段中,我需要将文本“作者说”替换为“关于作者”。 谢谢! <div id="author-info"> <div class="author-image"> <a class="author-avatar" href="https://www.test.com"><img alt=""></a> </div> <div class="author_name_wrap"> <h4 class="author_name"><a href="https://www.test.com/author/">Author say</a></h4> <div class="author_socicons"></div> </div> </div> 要更改 html 标签的内容,请使用 innerHTML 属性: var h4 = document.getElementsByClassName("author_name")[0], target = h4.childNodes[0]; target.innerHTML = "About the author"; 这是代码: document.getElementById("id-of-element").innerHTML = "new text"; <!DOCTYPE html> <html> <body> <p id="id-of-element">This text will be replaced</p> </body> </html> 这非常简单,您只需使用innerText或textcontent,如下例所示 //textConent Method const authorName = document.querySelectorAll('author_name').textContent="Text Here" //innerText Method const authorName = document.querySelectorAll('author_name').innerText="Text Here" 如果您使用jQuery,您可以轻松更改。 $("h4.author_name a").text('关于作者'); 您可以在这里找到详细的文章


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'); } 我要处理删除并提交数据更新数据库 在开始销毁表单之前关闭更新表单第一个表单标签(缺少)。


如何使用 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>


如何在不重新加载页面的情况下发送带有文件的表单?

我尝试在ajax中发送表单而不重新加载页面,但我看到,文件上的链接不存在...... 我有下一个表格: 我尝试在ajax中发送表单而不重新加载页面,但我看到,文件上的链接不存在... 我有下一个表格: <form id="settings" method="POST" enctype="multipart/form-data"> ... <input type="file" id="logo" style="display:none;" name="logo" accept="image/png, image/jpeg, image/gif"> <button type="submit" id="send" class="btn btn-primary">save</button> </form> Ajax 脚本: $('#settings').submit(function(e){ e.preventDefault(); var form = $(this).serialize(); alert(form); // file is not attached... $.ajax({ url : '/settings', type : 'POST', crossDomain : false, data : form, contentType : 'multipart/form-data', dataType : 'json', progressData: false, cache : false, success : function(r){ alert (111); } }).fail(function(){ console.log('Error occured!'); }); }); 在服务器端,我收到错误: org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为未找到多部分边界 我尝试不序列化表单,而是写了 data : form -> data : new FormData(this) 此选项会导致错误“非法调用”。如何在不重新加载页面的情况下发送带有文件的表单? 要使用 AJAX 发送带有文件的表单而不重新加载页面,您需要使用 FormData 来正确处理文件上传。 <form id="settings" method="POST" enctype="multipart/form-data"> <!-- Other form fields --> <input type="file" id="logo" name="logo" accept="image/png, image/jpeg, image/gif"> <button type="submit" id="send" class="btn btn-primary">Save</button> </form> $(document).ready(function() { $('#settings').submit(function(e){ e.preventDefault(); var formData = new FormData(this); $.ajax({ url: '/settings', type: 'POST', data: formData, contentType: false, processData: false, cache: false, success: function(response){ alert('Form submitted successfully!'); // Handle the response from the server }, error: function(){ console.log('Error occurred!'); } }); }); });


如何使用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 可能还有其他方法可以做到同样的事情。


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 请求。 检查浏览器开发者工具: 检查网络请求的路径和方法是否正确。 查找任何指示问题的错误或警告。


使用 InertiaJs 和 Laravel 从数据库中删除用户

我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: 我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: <Link class="trash" @click="submit(result.ChildID)"> Move to Trash </Link> 注意: ChildID 是数据库中子记录的 id。 现在:当用户单击此链接时,将调用一个方法,如下所示。 methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete('destroy/ChildID'); } }, }, 路线代码 Route::delete('destroy/{childID}',[childrenController::class,'destroy']); 控制器代码 public function destroy(children $childID){ $childID->delete(); return redirect()->route('View_Child_Profile'); } 现在,当我点击删除按钮时,我收到以下错误: 试试这个。我认为你犯了错误“this.$inertia.delete('destroy/ChildID');” methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete(`destroy/${ChildID}`); // or this.$inertia.delete('destroy/'+ChildID); } }, }, 这是我处理删除过程的方式。 前视+惯性: import { Link } from '@inertiajs/inertia-vue3'; 在模板中: <Link method="delete" :href="route('admin.insta_feeds.destroy',id)">Delete</Link> 后端 Laravel: 路线: Route::resource('insta_feeds', InstaFeedsController::class); 控制器功能: public function destroy(InstaFeed $insta_feed) { if(isset($insta_feed->image_path)){ Storage::delete($insta_feed->image_path); } $insta_feed->delete(); return Redirect::route('admin.insta_feeds.index'); }


.NET MAUI:自定义Shell TitleView并绑定到当前页面标题

我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: 我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: <?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="MyNamespace.App.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNamespace.App" xmlns:pages="clr-namespace:MyNamespace.App.Pages" BindingContext="{x:Static local:MainView.Instance}" Shell.FlyoutBehavior="{Binding ShellFlyoutType}" x:Name="shellMain"> <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" Text="{Binding Path=CurrentPage.Title, Mode=OneWay}" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> <ShellContent Title=" Login" ContentTemplate="{DataTemplate local:MainPage}" Route="login" FlyoutItemIsVisible="False" /> <ShellContent Title="Dashboard" ContentTemplate="{DataTemplate pages:DashboardPage}" Route="dashboard" /> </Shell> 我无法绑定当前页面标题。 我的 AppShell.xaml Shell 声明如下 <Shell ... x:Name="shellMain"> 作为替代方案,您可以在 OnNaviged 方法中设置 titleview : 在 AppShell.xaml 中,定义标签的名称 <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" x:Name="mylabel" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> 在AppShell.xaml.cs中,重写OnNaviged方法,获取当前项目 protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); var shellItem = Shell.Current?.CurrentItem; string title = shellItem?.Title; int iterationCount = 0; while (shellItem != null && title == null) { title = shellItem.Title; shellItem = shellItem.CurrentItem; if (iterationCount > 10) break; // max nesting reached iterationCount++; } myLabel.Text = title; } 希望它对你有用。 我正在尝试同样的方法来修改 TitleView 的外观。它可以在 iOS 上运行,尽管那里还有另一个错误。但在 Android 上我遇到了同样的问题。在前进导航中,它会更新标题,但当您按后退按钮时,标题不会更新。我已经打开了一个问题并添加了一个存储库。 https://github.com/dotnet/maui/issues/12416#issuecomment-1372627514 还有其他方法可以修改TitleView的外观吗? 我使用视图模型开发了这个解决方法,主要不是为了提供 MVVM 解决方案,而是因为其他建议的答案对我不起作用。 (我怀疑 Liqun Shen 2 月 15 日针对他自己的问题的评论中的建议会起作用。但我没有注意到这一点,直到我自己修复)。 当前页面的标题保存在可由 shell 的视图模型和每个内容页面的视图模型访问的类中: public class ServiceHelper { private static ServiceHelper? _default; public static ServiceHelper Default => _default ??= new ServiceHelper(); internal string CurrentPageTitle { get; set; } = string.Empty; } shell 中每个内容页面的视图模型提供其页面标题。为了促进这一点,大部分工作都是由基本视图模型完成的,它们都是从该模型派生而来的: public abstract class ViewModelBase(string title) : ObservableObject { private ServiceHelper? _serviceHelper; public string Title { get; } = title; internal ServiceHelper ServiceHelper { get => _serviceHelper ??= ServiceHelper.Default; set => _serviceHelper = value; // For unit testing. } public virtual void OnAppearing() { ServiceHelper.CurrentPageTitle = Title; } } 每个 shell 内容页面视图模型只需要让其基础视图模型知道它的标题: public class LocationsViewModel : ViewModelBase { public LocationsViewModel() : base("Locations") { } } 每个 shell 内容页面都需要在其视图模型中触发所需的事件响应方法: public partial class LocationsPage : ContentPage { private LocationsViewModel? _viewModel; public LocationsPage() { InitializeComponent(); } private LocationsViewModel ViewModel => _viewModel ??= (LocationsViewModel)BindingContext; protected override void OnAppearing() { base.OnAppearing(); ViewModel.OnAppearing(); } } Shell 的视图模型为标题栏提供当前页面的标题: public class AppShellViewModel() : ViewModelBase(Global.ApplicationTitle) { private string _currentPageTitle = string.Empty; public string CurrentPageTitle { get => _currentPageTitle; set { _currentPageTitle = value; OnPropertyChanged(); } } public void OnNavigated() { CurrentPageTitle = ServiceHelper.CurrentPageTitle; } } Shell 需要在其视图模型中触发所需的事件响应方法: public partial class AppShell : Shell { private AppShellViewModel? _viewModel; public AppShell() { InitializeComponent(); } private AppShellViewModel ViewModel => _viewModel ??= (AppShellViewModel)BindingContext; protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); ViewModel.OnNavigated(); } } 最后,Shell 的 XAML 在标题栏/导航栏上显示由 Shell 视图模型提供的当前页面的标题: <Shell.TitleView> <HorizontalStackLayout VerticalOptions="Fill"> <Image Source="falcon_svg_repo_com.png" HeightRequest="50"/> <Label x:Name="CurrentPageTitleLabel" Text="{Binding CurrentPageTitle}" FontSize="24" Margin="10,0" VerticalTextAlignment="Center"/> </HorizontalStackLayout> </Shell.TitleView>


从数据库中选择 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> 因此,如果父元素有一个选中的复选框,那么您可以定位与该父元素不同的子元素。


似乎无法让下载属性发挥作用

我刚刚开始学习 html 所以我想尝试使用 download 属性 我刚刚开始学习 html,所以我想尝试使用下载属性 <a href="../images/clunk.jfif" download="ur_mum"> <img src="../images/clunk.jfif" alt="ur mum" width="200" height="200"> </a> 图像存储在同一个网站上,但是当我单击它而不是下载时,它只会使图像全屏显示。 我尝试尽可能地排除故障,但没有成功 我能找到的关于为什么某些文件类型发生这种情况但并非所有文件类型的原因是这个答案关于pdf下载与预览的类似问题 - 如果可以的话,请将以下标头添加到服务器端的图像响应中: Content-Disposition: attachment; filename=clunk.jfif 或者,您可以使用自定义 onclick 处理程序替换锚标记,该处理程序将图像转换为数据 URL 并触发下载: <img src="../images/clunk.jfif" width="200" height="200" onclick="downloadImage(this)"> const downloadImage = async (img) => { // fetch the image's media type const mediaType = fetch(img.currentSrc, { method: 'HEAD' }) .then(res => res.headers.get('content-type')) .catch(() => 'image/png' /* default to png if request fails */) // place the image on a canvas element const canv = Object.assign(document.createElement('canvas'), { width: img.naturalWidth, height: img.naturalHeight, }) const ctx = canv.getContext('2d') ctx.drawImage(img, 0, 0) // download the canvas data const a = Object.assign(document.createElement('a'), { download: 'filename', href: canv.toDataURL(await mediaType), }) a.click() }


从数据库表中选择选择选项后如何显示/隐藏隐藏的 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() }


在 Rails 5 中单击浏览器上的后退按钮时,带有 Select2 的表单会重复

_header.html.erb(用于表单部分) <%= form_for home_path, class: 'home', role: 'search', method: :get do |f| %> _header.html.erb(用于表单部分) <%= form_for home_path, class: 'home', role: 'search', method: :get do |f| %> <div class="form-group" style="display:inline;"> <div class="input-group input-group-md"> <%= text_field_tag :q, params[:q], placeholder: ... ,class: 'form-control hideOverflow', type: "search" %> <%= select_tag "category", options_from_collection_for_select(...),include_blank: true, class: 'form-control hideOverflow', type: "search" %> <%if logged_in? %> <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', type: "search" %> <% else %> <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', include_blank: true, type: "search" %> <% end %> <span class="input-group-addon"><%= submit_tag "Search", class: "btn-transparent"%></span> </div> </div> <% end %> JS代码 <script> $( document ).on('turbolinks:load', function() { $('select#category').select2({ width: '60%', dropdownAutoWidth : true, placeholder: "Choose a category", maximumSelectionLength: 3 }); $('select#location').select2({ width: '40%', dropdownAutoWidth : true, minimumResultsForSearch: Infinity }); }); </script> 故障或渲染问题(单击链接查看图像) 有人可以帮我解决为什么吗?另外,我的搜索表单位于标题部分文件的导航栏中。 如果我去掉脚本中的 $(...).select ,一切都会正常...我认为 select.js 有问题 在此回复: https://stackoverflow.com/a/41915129/5758027 我在自己的代码中使用了这个解决方案: $(document).on('turbolinks:before-cache', function() { // this approach corrects the select 2 to be duplicated when clicking the back button. $('.select-select2').select2('destroy'); $('.select-search-select2').select2('destroy'); } ); 和观察者: $(document).ready( ready ); //... once document ready $(document).ajaxComplete( ready ); //... once ajax is complete $(document).on('turbolinks:load', ready ); //... once a link is clicked function ready() { $(".select-search-select2").select2({ theme: "bootstrap", language: 'es', allowClear: true }); $(".select-select2").select2({ theme: "bootstrap", language: 'es', minimumResultsForSearch: Infinity, allowClear: true }); }; 总是清除缓存不是会让使用 Turbolink 变得毫无意义吗? 不如这样? $(document).on('turbolinks:before-cache', function(e) { return $('.form-control.select2').each(function() { return $(this).select2('destroy'); }); }); 我无法解决这个渲染问题(仍在等待正确的答案!),但如果有人像我一样遇到类似的问题,请尝试跳出框框思考。这是我的技巧:我在应用程序中添加了一个后退按钮。 获取完整的url路径 # get the previous url def save_previous_page session[:return_to] = request.fullpath end 仅当页面不是主页或搜索页面时才显示后退按钮 <% if session[:return_to] != request.fullpath%> <%= link_to session.delete(:return_to) || request.fullpath, class: 'back-button' do%> <i class="fa fa-arrow-circle-left" aria-hidden="true"></i> <%end%> <% end %> 同时,我仍在等待并尝试解决渲染问题... 解决了问题 只需将此代码添加到您的 .js 文件中 Turbolinks.clearCache(); 这很可能是一些资源不一致,您应该检查您的 app\views\layouts 文件夹中是否有重复声明 wither jQuery、jQuery UJS 或 Turbolinks 的文件。检查页面的所有 <script> 标签,以及是否在 layout 文件夹和内部视图中声明相同的脚本。如果情况并非如此,请检查是否有 render、yield 或 build 呼叫 简单的解决方案,不要在您不希望它运行的东西上运行 select2 构建器。 $("select#category:not(.select2-container):not(.select2-hidden-accessible)").select2(); Rails 7 更新 这里的很多东西在 Rails 7 中都不起作用,尤其是 turbolinks:before-cache 事件。您正在寻找的新事件是 turbo:before-cache 和 turbo:load,所以它看起来像这样: $(document).on("turbo:before-cache", function() { $("#select_id").select2('destroy'); }); $(document).on('turbo:load', function() { $('#select_id').select2(); });


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 不在受保护区域中,则会显示它们。


如何在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对象


嵌套 useFetch 导致 Nuxt 3 中的 Hydration 节点不匹配

在 Nuxt 3 页面内,我通过从 pinia 存储调用操作来获取帖子数据: {{ 发布数据 }} {{ 帖子内容... 在 Nuxt 3 页面内,我通过从 pinia 商店调用操作来获取帖子数据: <template> <div v-if="postData && postContent"> {{ postData }} {{ postContent }} </div> </template> <script setup> const config = useRuntimeConfig() const route = useRoute() const slug = route.params.slug const url = config.public.wpApiUrl const contentStore = useContentStore() await contentStore.fetchPostData({ url, slug }) const postData = contentStore.postData const postContent = contentStore.postContent </script> 那是我的商店: import { defineStore } from 'pinia' export const useContentStore = defineStore('content',{ state: () => ({ postData: null, postContent: null }), actions: { async fetchPostData({ url, slug }) { try { const { data: postData, error } = await useFetch(`${url}/wp/v2/posts`, { query: { slug: slug }, transform(data) { return data.map((post) => ({ id: post.id, title: post.title.rendered, content: post.content.rendered, excerpt: post.excerpt.rendered, date: post.date, slug: post.slug, })); } }) this.postData = postData.value; if (postData && postData.value && postData.value.length && postData.value[0].id) { const {data: postContent} = await useFetch(`${url}/rl/v1/get?id=${postData.value[0].id}`, { method: 'POST', }); this.postContent = postContent.value; } } catch (error) { console.error('Error fetching post data:', error) } } } }); 浏览器中的输出正常,但我在浏览器控制台中收到以下错误: entry.js:54 [Vue warn]: Hydration node mismatch: - rendered on server: <!----> - expected on client: div at <[slug] onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > at <Anonymous key="/news/hello-world()" vnode= {__v_isVNode: true, __v_skip: true, type: {…}, props: {…}, key: null, …} route= {fullPath: '/news/hello-world', hash: '', query: {…}, name: 'news-slug', path: '/news/hello-world', …} ... > at <RouterView name=undefined route=undefined > at <NuxtPage> at <Default ref=Ref< undefined > > at <LayoutLoader key="default" layoutProps= {ref: RefImpl} name="default" > at <NuxtLayoutProvider layoutProps= {ref: RefImpl} key="default" name="default" ... > at <NuxtLayout> at <App key=3 > at <NuxtRoot> 如何解决这个问题? 我尝试在 onMounted 中获取帖子数据,但在这种情况下 postData 和 postContent 保持为空 onMounted(async () => { await contentStore.fetchPostData({ url, slug }) }) 您可以使用 ClientOnly 组件来消除该警告。请参阅文档了解更多信息。 该组件仅在客户端渲染其插槽。


在Java中将流转换为字符串

我想将 Map<> 的流转换为字符串,并将其附加到文本区域。我尝试了一些方法,最后一个使用 StringBuilder,但它们不起作用。 公开 我想将 Map<> 的流转换为字符串,并将其附加到文本区域。我尝试了一些方法,最后一个使用 StringBuilder,但它们不起作用。 public <K, V extends Comparable<? super V>> String sortByAscendentValue(Map<K, V> map, int maxSize) { StringBuilder sBuilder = new StringBuilder(); Stream<Map.Entry<K,V>> sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())); BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) sorted)); String read; try { while ((read=br.readLine()) != null) { //System.out.println(read); sBuilder.append(read); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sorted.limit(maxSize).forEach(System.out::println); return sBuilder.toString(); } 您可以将条目收集到一个String中,如下所示: String sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .map(e-> e.getKey().toString() + "=" + e.getValue().toString()) .collect(Collectors.joining (",")); 考虑对 @Eran 的代码进行轻微更改,因为 HashMap.Entry.toString() 已经通过 = 为您加入了: String sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .map(Objects::toString) .collect(Collectors.joining(",")); 这很容易做到,您可以使用 Steams API 来做到这一点。首先,将映射中的每个条目映射到单个字符串 - 键和值的连接字符串。一旦你有了这个,你就可以简单地使用 reduce() 方法或 collect() 方法来做到这一点。 使用“reduce()”方法的代码片段将如下所示: Map<String, String> map = new HashMap<>(); map.put("sam1", "sam1"); map.put("sam2", "sam2"); String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .reduce("", (str1,str2) -> str1 + " , " + str2).substring(3); System.out.println(concatString); 这将为您提供以下输出: sam2 : sam2 , sam1 : sam1 您还可以使用 collect()' method instead ofreduce()` 方法。它看起来像这样: String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .collect(Collectors.reducing("", (str1,str2) -> str1 + " , " + str2)).substring(3); 两种方法给出相同的输出。


替换字符串后在 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 ]+)。


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

希望这不是一个愚蠢的问题,但我已经没有主意了...... 所以我有这个模式: 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 });


Laravel POST 方法返回状态:405 不允许在 POST 方法上使用方法

请查找以下信息: NoteController.php 请查找以下信息: NoteController.php <?php namespace App\Http\Controllers; use App\Http\Requests\NoteRequest; use App\Models\Note; use Illuminate\Http\JsonResponse; class NoteController extends Controller { public function index():JsonResponse { $notes = Note::all(); return response()->json($notes, 200); } public function store(NoteRequest $request):JsonResponse { $note = Note::create( $request->all() ); return response()->json([ 'success' => true, 'data' => $note ], 201); } public function show($id):JsonResponse { $note = Note::find($id); return response()->json($note, 200); } public function update(NoteRequest $request, $id):JsonResponse { $note = Note::find($id); $note->update($request->all()); return response()->json([ 'success' => true, 'data' => $note, ], 200); } public function destroy($id):JsonResponse { Note::find($id)->delete(); return response()->json([ 'success' => true ], 200); } } NoteRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class NoteRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'title', 'required|max:255|min:3', 'content', 'nullable|max:255|min:10', ]; } } Note.php(模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Note extends Model { use HasFactory; protected $guarded = []; } api.php <?php use App\Http\Controllers\NoteController; use Illuminate\Support\Facades\Route; Route::prefix('v1')->group(function () { Route::resource('/note', NoteController::class); }); php artisan 路线:列表 GET|HEAD / ...................................................................................................................... POST _ignition/execute-solution ............... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController GET|HEAD _ignition/health-check ........................... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController POST _ignition/update-config ........................ ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController GET|HEAD api/v1/note .......................................................................... note.index › NoteController@index POST api/v1/note .......................................................................... note.store › NoteController@store GET|HEAD api/v1/note/create ................................................................. note.create › NoteController@create GET|HEAD api/v1/note/{note} ..................................................................... note.show › NoteController@show PUT|PATCH api/v1/note/{note} ................................................................. note.update › NoteController@update DELETE api/v1/note/{note} ............................................................... note.destroy › NoteController@destroy GET|HEAD api/v1/note/{note}/edit ................................................................ note.edit › NoteController@edit GET|HEAD sanctum/csrf-cookie .................................. sanctum.csrf-cookie › Laravel\Sanctum › CsrfCookieController@show 迅雷请求(同邮递员) JSON 请求 { "title": "Hello World", "content": "Lorem ipsum." } 尝试发出 JSON POST 请求并获取状态:405 方法不允许并且我正在使用 php artisan 服务,如果需要,我可以提供 GIT 项目。请告诉我。 您的验证规则看起来不正确。在您的 NoteRequest 类中,规则应该是一个关联数组,其中键是字段名称,值是验证规则。但是,在您的代码中,规则被定义为以逗号分隔的字符串列表。这可能会导致验证失败并返回 405 Method Not allowed 错误。 public function rules() { return [ 'title' => 'required|max:255|min:3', 'content' => 'nullable|max:255|min:10', ]; }


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 请求没有正文,而这就是文件所在的位置


更新 MyBatis 中的值列表 - SQLSyntaxErrorException

更新 MyBatis 中的值列表时出现 SQLSyntaxErrorException。我正在使用分隔符=“;”在 forecach 标签中,但我仍然收到错误。下面是我的sql查询 更新 MyBatis 中的值列表时出现 SQLSyntaxErrorException。我在 forecach 标签中使用 separator=";" ,但仍然收到错误。下面是我的sql查询 <update id="updateComplianceCheckListResponse" parameterType="java.util.List"> <foreach collection="list" item="response" separator=";"> UPDATE AM_ComplianceChecklistResponse SET complianceDetailsId = #{response.complianceDetailsId}, complianceChecklistId = #{response.complianceChecklistId}, questionResponse = #{response.questionResponse}, expiryDate = #{response.expiryDate}, documentName = #{response.documentName}, comments = #{response.comments} WHERE id = #{response.id} </foreach> </update> org.apache.ibatis.exceptions.PersistenceException: 更新数据库时出错。原因:java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在“UPDATE AM_ComplianceChecklistResponse”附近使用的正确语法 SET complianceDetailsId = 1, com' at line 10 错误可能存在于 com/am/dao/managecompliance/ComplianceChecklistResponse.xml 中 错误可能涉及ComplianceChecklistResponse.updateComplianceCheckListResponse-Inline 设置参数时出现错误 SQL: UPDATE AM_ComplianceChecklistResponse SETcomplianceDetailsId = ?,complianceChecklistId = ?,questionResponse = ?,expiryDate = ?,documentName = ?,comments = ?哪里 id = ? ; UPDATE AM_ComplianceChecklistResponse SET complianceDetailsId = ?、complianceChecklistId = ?、questionResponse = ?、expiryDate = ?、documentName = ?、comments = ?哪里 id = ? 原因:java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在“UPDATE AM_ComplianceChecklistResponse”附近使用的正确语法 SET complianceDetailsId = 1, com' at line 10 at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:196) at com.am.dao.managecompliance.ComplianceChecklistResponseDAO.updateComplianceCheckListResponse(ComplianceChecklistResponseDAO.java:50) at com.am.service.managecompliance.ComplianceChecklistResponseService.updateComplianceCheckListResponse(ComplianceChecklistResponseService.java:122) at com.am.webservice.controller.managecompliance.ManageComplianceController.updateComplianceCheckListResponse(ManageComplianceController.java:230) at com.am.webservice.controller.managecompliance.ManageComplianceController$$FastClassBySpringCGLIB$$e3100610.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386) at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704) at com.am.webservice.controller.managecompliance.ManageComplianceController$$EnhancerBySpringCGLIB$$4a5751a4.updateComplianceCheckListResponse(<generated>) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:555) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:623) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:209) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:337) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at com.dbp.security.auth.spring.StatelessAuthenticationFilter.doFilter(StatelessAuthenticationFilter.java:55) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:221) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:168) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:481) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:130) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:670) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1794) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:833) 引起:java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在“UPDATE AM_ComplianceChecklistResponse”附近使用的正确语法 设置合规性详细信息 ID = 1, com' 在第 10 行 在 com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) 在com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) 在com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916) 在 com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:354) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) 在java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:568) 在org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59) 在 jdk.proxy5/jdk.proxy5.$Proxy81.execute(来源未知) 在 org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:47) 在 org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74) 在 org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50) 在 org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117) 在 org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76) 在 org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:194) ...省略69个常用框架 修复为 <insert id="updateComplianceCheckListResponse" parameterType="java.util.List"> insert into AM_ComplianceChecklistResponse (id,complianceDetailsId,complianceChecklistId,questionResponse,expiryDate,documentName,comments) VALUES <foreach collection="list" item="response" separator="," open="(" close=")"> #{response.id}, #{response.complianceDetailsId},#{response.complianceChecklistId},#{response.questionResponse},#{response.expiryDate},#{response.documentName},#{response.comments} </foreach> on duplicate key update complianceDetailsId= VALUES(complianceDetailsId), complianceChecklistId=VALUES(complianceChecklistId), questionResponse=VALUES(questionResponse), expiryDate=VALUES(expiryDate), documentName=VALUES(documentName), comments=VALUES(comments) </insert>


在 .NET 6 中使用 xsltc.exe 生成的程序集(XSLT 样式表)

我有一个 XSLT 样式表“Stylesheet.xsl”,我已使用 xsltc.exe 将其编译为“Stylesheet.dll” 该 DLL 包含在我的 .NET 6 中(net6.0 我有一个 XSLT 样式表“Stylesheet.xsl”,我已使用 xsltc.exe 将其编译为“Stylesheet.dll” 该 DLL 包含在我的 .NET 6 (<TargetFramework>net6.0</TargetFramework>) 项目中,用法如下: var xslCompiledTransform = new XslCompiledTransform(); xslCompiledTransform.Load(typeof(Stylesheet)); // ↑ System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.SqlXml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified. xslCompiledTransform.Transform(@"..\..\..\input.xml", @"..\..\..\output.xml"); Load方法抛出FileNotFoundException,并显示消息“无法加载文件或程序集‘System.Data.SqlXml,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089’。系统找不到指定的文件。 ” 关于 xsltc.exe 的文档说明了以下内容: 脚本块仅在 .NET Framework 中受支持。 .NET Core 或 .NET 5 或更高版本不支持它们。 这严重暗示使用 xsltc.exe 编译的样式表应该在 .NET Core 或 .NET 5 或更高版本上工作(当不使用脚本块时),但在我的测试中却不起作用。 有谁知道为什么使用 xsltc.exe 编译的样式表不适用于 .NET 6 以及如何解决此问题? 更多详情 我在下面添加了有关我尝试过的更多详细信息。 请注意,我使用的样式表Stylesheet.xsl非常基本,没有使用特殊功能:<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:template match="/"> <output> <xsl:for-each select="input/book"> <booktitle> <xsl:value-of select="@title" /> </booktitle> </xsl:for-each> </output> </xsl:template> </xsl:stylesheet> 生成DLL的命令: "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\xsltc.exe" Stylesheet.xsl 在 SDK 样式的 .csproj 文件中引用 DLL: <ItemGroup> <Reference Include="Stylesheet"> <HintPath>.\Stylesheet.dll</HintPath> </Reference> </ItemGroup> input.xml:<input> <book title="First Title" /> <book title="Second Title" /> </input> output.xml 使用未编译的样式表执行转换时:<output> <booktitle>First Title</booktitle> <booktitle>Second Title</booktitle> </output> 我已经研究并发现其他人也有同样的问题,但还没有找到解决方案或解释为什么 Microsoft 文档隐式声明它应该可以工作,而在我的测试中却不起作用。 https://github.com/dotnet/runtime/issues/68129 在.NET Core 2.2中使用xsltc.exe生成的程序集? XslCompiledTransform.Load(type):无法加载文件或程序集“System.Data.SqlXml” System.IO.FileNotFoundException的堆栈跟踪: at System.Delegate.BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags) at System.Reflection.RuntimeMethodInfo.CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags) at System.Reflection.RuntimeMethodInfo.CreateDelegate(Type delegateType) at System.Xml.Xsl.XslCompiledTransform.Load(MethodInfo executeMethod, Byte[] queryData, Type[] earlyBoundTypes) at System.Xml.Xsl.XslCompiledTransform.Load(Type compiledStylesheet) at TestXslDotnet6.Program.Main(String[] args) in C:\Users\UserNameRedacted\Path\To\Repo\TestXslDotnet6\TestXslDotnet6\Program.cs:line 10 根据 GitHub 问题 .NET 6 不支持 XslCompiledTransform.Load(type(myXsltCompiled_dll)) 中的信息,看起来好像不支持,也不会支持。 2022年4月18日的评论说: 程序集 System.Data.SqlXml 包含命名空间 System.Xml.Xsl.Runtime,该命名空间在 .NET Core 中不存在。 根据移植指南,msxsl:script 在 .NET Core 上不可用。 .NET Framework 特定教程预计不起作用。 第二个人评论: 看起来 System.Data.SqlXml 是 SQLXML 的一部分,属于 据我所知,SQL Server org 不支持 .NET Core。 第三个人回复: 目前没有关于 SQLXML 和对 .NET 5+ 支持的计划, 我们还没有听到很多这方面的请求。我会 建议在此处开放用户声音以获得一些吸引力并 关于该主题的共识:https://aka.ms/sqlfeedback 所以,这就是您的答案:“msxsl:script 在 .NET Core 上不可用。.NET Framework 特定教程预计不起作用。”原因是非 .NET 组织必须使其成为可能,但没有计划这样做。他们没有意识到需求。 而且,他们承认该文档具有误导性。似乎在 2022 年 5 月对文档进行了更改,并创建了拉取请求:请注意,XSLT 脚本块仅限 .NET Framework。 我认识到这并没有为您提供解决方案或前进的道路,这令人失望。但这就是您问题的答案:.NET 6.0 根本不支持以这种方式进行转换。 虽然距离这个问题大约有两年了,但我还是想分享一下我为自己的目的所做的解决方法,因为我没有找到任何其他解决方案,可以帮助在基于 .NET Core 的转换中使用编译的 xslt dll。 因此,如果您想将 XslCompiledTransform 类与通过 xlstc.exe 生成的 dll 类型一起使用,请按照以下步骤操作: 生成dll类 xsltc.exe /class:Transform /out:Your.Assembly.dll 将 dll 反汇编为 ILL 代码 ildasm Your.Assembly.dll /out=Your.Assembly.ill 将 Your.Assembly.ill 中所有出现的 [System.Data.SqlXml] 替换为 [System.Private.Xml] 将你的IL编译回dll ilasm Your.Assembly.ill /dll 现在您可以将 Your.Assembly.dll 引用添加到您的 .NET Core 项目


在 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.