Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在JavaScript中使用Phoenix控制器变量?_Reactjs_Elixir_Phoenix Framework - Fatal编程技术网

Reactjs 如何在JavaScript中使用Phoenix控制器变量?

Reactjs 如何在JavaScript中使用Phoenix控制器变量?,reactjs,elixir,phoenix-framework,Reactjs,Elixir,Phoenix Framework,如何在JavaScript中使用Phoenix controller中的变量 我使用React作为前端 我不能在JavaScript中使用 defmodule Familytree.PageController do use Familytree.Web, :controller alias Familytree.Users alias Familytree.Tags alias Familytree.UserTag plug Familytree.Plugs.Auth

如何在JavaScript中使用Phoenix controller中的变量

我使用React作为前端

我不能在JavaScript中使用

defmodule Familytree.PageController do
  use Familytree.Web, :controller

  alias Familytree.Users
  alias Familytree.Tags
  alias Familytree.UserTag

  plug Familytree.Plugs.Auth
  plug :scrub_params, "users" when action in [:create, :update]
  plug :scrub_params, "tags" when action in [:add_tag,:delete_tag]

  def index(conn, _params) do
    users = Repo.all(Users)
    tags = Repo.all(Tags)
    render(conn, "index.html", users: users, tags: tags, current_user: get_session(conn, :current_user))
  end
end

您可以尝试在视图中呈现该值以构建HTML属性,然后使用JavaScript获得该属性,这是非常常见的做法

这样做可以:

my_view.eex

您可以找到有关
数据的更多信息

希望有帮助

您可以使用它将所有phoenix变量带到窗口范围,您可以使用所有这些变量,它还可以生成获取这些变量的js方法:

def index(conn, _params) do
  put_gon(conn, [users: Repo.all(Users), tags: Repo.all(Tags)])
  render(conn, "index.html", current_user: get_session(conn, :current_user))
end
并在浏览器控制台或javascript模块中使用:

window.Gon.getAsset('users')
// => [user, user1 ...]

它还有助于将js变量和html.eex变量放在不同的部分并保持清晰。

是的,这对我来说不起作用。也许我做错了什么我不知道。当我写这行时,我得到了一个论点error@ake你收到了什么样的错误?你能提供更多的信息和粘贴更多的代码(例如从你的控制器)?当我写这行:我得到这个错误分配@user不可用的eex模板。在我的控制器中,我有:alias Familytree.Users,这是我在JavaScription中需要使用的所有信息。恐怕这并不能提供我需要帮助您的所有信息。您是否能够编辑您的问题并提供更丰富的代码片段?这可能会有很大帮助。@ake,快速浏览您的文件似乎您在控制器中设置了
用户
,但在您看来,您正试图访问
用户
,因此,您在eex模板中看到
错误分配@user not available
的原因是您想在初始页面加载时只加载一次数据吗?是的。我需要那个对象,因为我在搜索栏,所以我需要那个对象的所有名称
def index(conn, _params) do
  put_gon(conn, [users: Repo.all(Users), tags: Repo.all(Tags)])
  render(conn, "index.html", current_user: get_session(conn, :current_user))
end
window.Gon.getAsset('users')
// => [user, user1 ...]