繁体   English   中英

无法在Rails 5中将Json数据获取到Ajax

[英]Can't get Json data to Ajax in Rails 5

嗨,我试图用Ajax理解和实现Rails动作控制器。 我的问题是为什么我无法获取Json数据并将其显示在我的Ajax函数中的console.log中。 我将ajax函数放在application.js文件中。 我的ajax get方法工作正常,但post方法似乎不起作用。 在文章索引页面中,当您单击新文章时,它将呈现部分格式,并且ajax将与控制器中的create动作进行通信,以将数据追加到索引页面。 但是我无法将Json数据解析到Ajax发布。 这是我的代码文件: 更新的图像 在此处输入图像描述当我单击“网络”选项卡中的“仅创建json数据”时。 Alert和console.log没有显示任何内容。

application.js

$(function (){
var $article_table = $('#article_table');
$.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/articles',
    success: function(articles){
        $.each(articles, function(i, article) {
            $article_table.append('<tr><td>'+article.name+'</td></tr>')
        });
    }
});
$('#form_article').submit(function(){
    //var name = $('#article_name').val();
    var name = JSON.parse(xhr.responseText);
    $.ajax({
        type: 'POST',
        url: '/articles',
        dataType: 'json',
        data: name,
        success: function(data){
            //alert(data.id);
            console.log('success',data);
            //debugger;
        },
        error: function(){

        }
    });
});

Articles_controller.rb =>在创建控制器中,我将文章渲染为json

   class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.all
  end

  def show
  end

  # GET /articles/new
  def new
    @article = Article.new
  end

  # GET /articles/1/edit
  def edit
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(article_params)

    #respond_to do |format|
      if @article.save
        #format.html { redirect_to @article, notice: 'Article was successfully created.' }
        #format.json { render :show, status: :created, location: @article }
        #format.html
        #format.json { render json: @article, status: :ok}
        render json: @article, status: :ok
      else
        #format.html { render :new }
        #format.html
        render json: @article.errors, status: :unprocessable_entity
        #format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    #end
  end

_form.html.erb:

    <%= form_with(model: @article, remote: true , id: :form_article) do |form| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% @article.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :article_name %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

index.html.erb:

<p id="notice"><%= notice %></p>

<h1>Articles</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody id="article_table">

  </tbody>
</table>

<br>

<%= link_to 'New Article', new_article_path, id: :new_article_link, remote: true %>

new.js.erb:

 $('#new_article_link').hide().after("<%= j render 'form' %>");

您需要像这样传递数据

data: {article: {name: name}}

在jQuery / AJAX部分上,请参见以下内容

$('#form_article').submit(function(){
    // Declare a variable for get data from input field
    var name = $('#article_name').val();
    $.ajax({
        type: 'POST',
        url: '/articles',
        dataType: 'json',
        data: {article: {name: name}},
        success: function(data){
            //alert(data.id);
            //console.log('success', data);
            console.log(JSON.stringify(data));
            //debugger;
        },
        error: function(){
            alert("Error");
        }
    });
});

希望能帮助到你

暂无
暂无

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

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