我有一个包含图像的页面。在每个图像中,都有一个 onClick 事件和一个用于查看该菜谱详细信息的 id。当您单击时,它会通过 AJAX 到达 Controller 中的操作,从而使用 Twig 创建一个新 View 。问题是它不会重新加载(不是提交按钮),并且当我将响应分配给 html 时,新页面开头的菜单不起作用。而且,此外,不会更改 URL(仅当我做了那个棘手的 window.history.pushState,并且在刷新页面之前无法回溯历史记录)
HTML
<img src="{{recipe.image}}" onclick="showDetail()" id={{recipe.id}}>
JS
function showDetail() {
var detailId = $(event.target).attr('id');
$.ajax({
type: "post",
url: "showDetail",
dataType: "html",
data: {id:detailId},
success: function(res){
// $("html").html(res); // this one makes menus don't work
},
error: function(jqXHR, textStatus, errorThrown){ $("#respRecipe").html(textStatus + ' ' + jqXHR.status + ' ' + errorThrown); }
});
Controller
public function showDetailAction($params) {
$model = new DetailModel;
$recipeData = $model->recipeDataDB($params["id"]);
View::renderTwig('Detail/detail.html', array('recipeData'=>$recipeData[0],
'ingredientsData'=>$recipeData[1], 'commentsData'=>$recipeData[2]));
}
routes.json(我可以更改此参数以接受参数而不需要 AJAX 吗?)
"showDetail": {
"controller": "DetailController",
"action": "showDetail"
},
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([a-zA-Z0-9\-\_\/]*)$ index.php?p=$1
</IfModule>
我不知道是否可以,但图像内有一个隐藏的提交按钮...主要问题是刷新页面、URL 和工作菜单。
提前致谢。
最佳答案
The problem is that it doesn't reload (not submit button), and when i assign the response to html, the menus at the beginning of the new page don't work.
使用 Ajax 调用,页面不会重新加载。 Ajax 应该发出请求并获取响应而无需重新加载
And, in addition, doesn't change the URL (only if I make that tricky window.history.pushState, and doesn't work going history back until you refresh page)
通常使用 Ajax,我们不会更改 URL,除非我们打算转到不同的页面路由。
如果您得到正确的响应,则可以更改 html 标记的内容。
关于javascript - 将参数传递给 MVC PHP Controller 并打开新页面而不使用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61667005/