【问题标题】:How to load a view through ajax with data如何通过带有数据的ajax加载视图
【发布时间】:2018-07-28 20:08:06
【问题描述】:

当我单击 div 时,我想在当前页面下方加载另一个页面内容。

当您单击 .work-item div 时,它将获取 id 并将数据从 work/getListData 函数获取到该相关 id,以便该函数将返回带有相关数据的 json 编码数据对象。现在我想将它们传递给 detail-view,php 并在 .work-item div 下方显示它

请指教

//js

$(".work-item").live('click', function () {
  var id= this.id;
  $.ajax({
    type: 'GET',
    url: '/work/getistData/',
    data: {id : id},
    success: function (data) {
      var json_obj = $.parseJSON(data);
      console.log(data);
    }
  });
});

//controller 
public function listpage ($data) { 
  //this will give a page
}

public function getistData () { 
  $id = $this->request->getQuery('id');
  $data = $this->helper->fetchList($id )
  // echo json_encode($data);
  return $this->listpage($data);
}

【问题讨论】:

  • 使用$$ 是否有特定原因?此外,我建议不要回复result,而是建议return
  • @fab $$ 这是拼写错误,我已更正。我只是通过传递获取的数据来更新我的函数。 listData() 函数返回视图。但是可以通过ajax返回那个页面吗?
  • 好吧,您可以将 html 作为结果或 JSON 对象传递。因此,html结构要么从服务器返回,要么通过JS在本地创建。您的 listpage 函数可以在服务器端生成 html 代码。这取决于您的用例。此外,您的getListData 有错字,缺少;

标签: javascript php jquery ajax


【解决方案1】:

如果我正确理解了你的问题,那么你应该在你的 AJAX 成功函数中执行这段代码:

let div = document.createElement("div");
div.innerHTML = data;
document.getElementsByTagName("body")[0].appendChild(div);

【讨论】:

    【解决方案2】:

    这是我在 SO 中的第一个答案。

    通常我首先要做的是将问题分解成小块。测试,如果成功则继续。

    第 1 步:

    console.log(id)
    
    • 在您的 JavaScript 点击回调中,确保您获得正确的 ID。

    在 jQuery 中:

    var id = $(this).attr("id"); //if your required id in HTML id element.

    var id = $(this).data("id"); //if your required id in HTML data-id element.

    第 2 步:我不确定您的 PHP 函数名称是 getistData() 还是 getListData()。

    第 3 步: var_dump($id) 在您的 PHP getistData() 函数中,确保您收到正确的 id。

    我个人认为如果你使用GET,你也可以这样发送参数:

    在 JavaScript 中:

    url: '/work/getistData/' + id,

    然后在 php 中接收 => getistData($id)

    第四步:我不知道你为什么在

    中使用$$
    $$this->helper->fetchList($id)
    

    第五步:我确定正确的函数是JSON.parse()

    你应该写:

    var json_obj = JSON.parse(data);
    

    那好吧。祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2013-07-20
      • 1970-01-01
      • 2019-01-15
      相关资源
      最近更新 更多