我试图使用escape_javascript/1,但收到错误。
这是我的' poster_controller.ex'动作:
def index(conn, params) do
posts = Repo.all(Post)
render conn, %{posts: posts}
end
相应的' poster_view.ex':
def render("index.json", %{posts: posts}) do
render("index.js", %{})
end
注意 - 在我让渲染工作之前,我没有将帖子传递到模板中。
以下是被触发的js" index.js.eex':
$("#foobar").append("<%= escape_javascript(render("foobar.html", %{})) %>");
我尝试渲染的模板&fo; foobar.html.eex&#39;:
<h2>i was placed dynamically</h2>
我尝试渲染的模板foobar.html.eex&#39;于:
<div id="foobar"></div>
我看到的错误:
[info] Sent 500 in 8ms
[error] #PID<0.994.0> running Blog.Endpoint terminated
Server: localhost:4000 (http)
Request: GET /api/posters
** (exit) an exception was raised:
** (Poison.EncodeError) unable to encode value: {:safe, [[["" | "$(\"#foobar\").append(\""] | "<h2>i was placed dynamically<\\/h2>\\n"] | "\");\n"]}
(poison) lib/poison/encoder.ex:354: Poison.Encoder.Any.encode/2
(poison) lib/poison.ex:41: Poison.encode!/2
(phoenix) lib/phoenix/controller.ex:642: Phoenix.Controller.do_render/4
(blog) web/controllers/poster_controller.ex:1: Blog.PosterController.action/2
(blog) web/controllers/poster_controller.ex:1: Blog.PosterController.phoenix_controller_pipeline/2
(blog) lib/blog/endpoint.ex:1: Blog.Endpoint.instrument/4
(blog) lib/phoenix/router.ex:261: Blog.Router.dispatch/2
(blog) web/router.ex:1: Blog.Router.do_call/2
(blog) lib/blog/endpoint.ex:1: Blog.Endpoint.phoenix_pipeline/1
(blog) lib/plug/debugger.ex:123: Blog.Endpoint."call (overridable 3)"/2
(blog) lib/blog/endpoint.ex:1: Blog.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /Users/alang/projects/elixir/blog/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
答案 0 :(得分:0)
试试这个
$("#foobar").append("<%= escape_javascript(render('foobar.html')) %>");