简体   繁体   English

在Rails中在自动完成结果中添加link_to标记

[英]Adding link_to tag in autocomplete results in Rails

I'm trying to add link to show page in autocomplete results. 我正在尝试添加链接以在自动完成结果中显示页面。 But its not working. 但是它不起作用。 I post my code below. 我在下面发布我的代码。 But i tried to check whether my jquery is getting executed with an alert box. 但是我试图检查我的jquery是否正在使用警告框执行。 it works fine. 它工作正常。 But when i tried to add css for some div using jquery I cant. 但是,当我尝试使用jQuery为某些div添加css时,我无法进行。

//application.js //application.js

    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var key = JSON.parse(xmlhttp.responseText);
            document.getElementById("search-display").innerHTML = "";
        }
        if(key.length == 0){
            document.getElementById("search-display").innerHTML = "No results found";
        }
        for( var i=0; i < key.length; i++){
            var display = key[i].firstname + "&nbsp&nbsp" + key[i].mobilenumber + 
               "\n" <%= link_to 'show', contact_path(@contact) %>;   //this line is not working

            document.getElementById("search-display").innerHTML += display;

            $(document).ready(function(){
                // alert("hello");
                **$("#search-display").css('background','white');** //this line is not getting executed 
            });

        }
    }

This JavaScript is running on the client machine. 该JavaScript正在客户端计算机上运行。 It does not have access to Rails helpers. 它无权访问Rails助手。 You can build the full URL on the server side ( in your controller ) and send it in the JSON response. 您可以在服务器端(在控制器中)构建完整的URL,并在JSON响应中发送它。

The javascript is running on the client browser. javascript正在客户端浏览器上运行。
It doesn't know anything about Ruby on Rails and doesn't have any idea what the link_to stuff is about. 它对Ruby on Rails一无所知,也不知道link_to含义是什么。

The approach you should use in these cases is: 在这些情况下应使用的方法是:

  1. A link that that calls javascript 调用javascript的链接
  2. Any required javascript needed at that point (disabling a link or a search button is a frequent action here) is done as needed and then rails is called with a GET 此时需要执行的所有必需的javascript(在此处禁用链接或搜索按钮都是经常的操作),然后使用GET调用rails
  3. Receive any response from the rails server in JSON 接收来自Rails服务器的JSON响应
  4. Use the JSON info (sometimes) to then update the screen further. 使用JSON信息(有时)来进一步更新屏幕。 for example remove checkboxes or populate a dropdown list of suggestions (as needed in your case). 例如,删除复选框或填充建议下拉列表(根据您的情况)。

Which you do when depends on your specific needs. 何时执行操作取决于您的特定需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM