javascript - 将参数传递给 MVC PHP Controller 并打开新页面而不使用提交按钮

标签 javascript php jquery twig

我有一个包含图像的页面。在每个图像中,都有一个 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/

相关文章:

jquery - 为什么我的 DIV 叠加层不起作用?

php - 如何创建仅包含字母和数字的加密器和解密器?与此相同(ABQIAAAA5SlC01zPdiQe2c6gr56AAhSc)

javascript - .Remove() 无法删除具有集合形式的 id 的文本框

php - 幻想联盟和设计实现的表格

php - Wordpress 主菜单 - 仅在主页上隐藏 'Home' 链接

php - 如何从已经运行的实例中执行 matlab 代码?

javascript - 为什么使用jquery的html可以运行脚本,但使用innerHTML却不能运行脚本?

javascript - 如果输入的值与任何文本匹配,如何显示错误消息?

javascript - 使用 jQuery 将复杂的标点字符串拆分为大于 2 个字符的常规单词

jquery - jquery Selectbox获取所有选项值