dtgsl60240 2014-05-27 08:54
浏览 123
已采纳

用链接调用ajax函数

I am trying to create an ajax function with all the data inside the following variable inside the following function: $item

public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
{
    $view = JRequest::getVar('view');

    if($view === 'item'){
        $db = JFactory::getDbo();
        $query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
        $db->setQuery($query);
        $resultado = $db->loadResult();

        echo '<input class=subscribete type=button id='.$resultado.'-'.$item->id.' value="Subscribete" />'; 
    }
}

Im not sure if instead of using a <button> I should use an html link. The variable $item is an object with a lot of information which I want to take to my AJAX for later treating this data...

  • 写回答

2条回答 默认 最新

  • doupaxia2478 2014-05-27 09:59
    关注

    You can use either the anchor or the button element, it depends on your requirement. User always expect web page will direct to another page or popup something after click anchor and trigger a action (form submit, show/hide content...etc) after click a button. Please note you should call event.preventDefault() in click event handler in order to avoid appending unnecessary "#" to url when you're using anchor element as a AJAX caller.

    Then you need to store the AJAX call required data to DOM by using custom data attribute in PHP. (Assume that you only need the ID of $item)

    public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
    {
      $view = JRequest::getVar('view');
    
      if($view === 'item'){
        $db = JFactory::getDbo();
        $query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
        $db->setQuery($query);
        $resultado = $db->loadResult();
    
        //add required data to DOM
        echo '<input class="subscribete" type="button" id="'.$resultado.'-'.$item->id.'" value="Subscribete" data-id="'.$item->id.'"/>'; 
      }
    }
    

    Final step, register the click event handler of DOM which will trigger a AJAX call.

    $(function(){
      $(".subscribete").click(function(e){
        if(this.tagName==="A"){
          e.preventDefault();
        }
    
        //$(this).data("key") will return the value at the named data which is set by HTML5 data-* attribute
        $.ajax({
          url: "http://path.to.ur/url",
          type: "POST",
          data: {id:$(this).data("id")},
          success: function(response){
            alert(response);
          },
          error: function(jqXhr,status,error){
            alert(error);
          }  
        });
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料