使用jquery ajax post在Phoenix Framework中提交POST请求

mes*_*ros 13 ajax jquery elixir phoenix-framework

我们希望使用我们的内容可编辑,利用router.ex中生成的以下路由:

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end
  scope "/", TextEditor do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
    resources "/posts", PostController
  end
Run Code Online (Sandbox Code Playgroud)

和控制器功能,即创建:

  def create(conn, %{"post" => post_params}) do
    changeset = Post.changeset(%Post{}, post_params)

    case Repo.insert(changeset) do
      {:ok, _post} ->
        conn
        |> put_flash(:info, "Post created successfully.")
        |> redirect(to: post_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end
Run Code Online (Sandbox Code Playgroud)

但是我们不想使用生成的表单,然后我们尝试使用div和jquery方法$ .post来测试它:

<div id="newPost" contenteditable="true">write here</div>
<div id="button" class="btn btn-primary">Save</div>

<script type="text/javascript">
$(document).ready(function(){
  $("#button").click(function() {
    var post = $("#newPost").html();

    $.post( "/posts/post", { title: post })
     .done(function() {
        alert( "Data Loaded: " );
    });
  });
});
</script>
Run Code Online (Sandbox Code Playgroud)

但是,我们没有收到警报或任何数据插入我们的数据库.我们缺少什么?

编辑:在浏览器管道中,我们删除了交叉伪造插件,因为csrf令牌错误.

Gaz*_*ler 20

请尝试以下方法:

$.post( "/posts", { post: { title: post } })
Run Code Online (Sandbox Code Playgroud)

您的控制器希望参数嵌套在一个键下 post

def create(conn, %{"post" => post_params}) do
Run Code Online (Sandbox Code Playgroud)

我不建议这样做,但您可以将控制器更改为:

def create(conn, %{} = post_params) do
Run Code Online (Sandbox Code Playgroud)

在没有根post密钥的情况下查找参数.但是,使用post密钥意味着您可以轻松地获得与表单无关的其他参数.

我也不建议禁用CSRF检查.您可以通过将其存储在元标记中轻松提交CSRF令牌:

<meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>">
Run Code Online (Sandbox Code Playgroud)

然后将其作为标题添加到您的帖子请求中:

var csrf = document.querySelector("meta[name=csrf]").content;

$.ajax({
    url: "/posts",
    type: "post",
    data: {
      post: { title: post } })
    },
    headers: {
        "X-CSRF-TOKEN": csrf 
    },
    dataType: "json",
    success: function (data) {
      console.log(data);
    }
});
Run Code Online (Sandbox Code Playgroud)