Javascript Can';t在Rails 5中将Json数据获取到Ajax

Javascript Can';t在Rails 5中将Json数据获取到Ajax,javascript,jquery,ruby-on-rails,json,ajax,Javascript,Jquery,Ruby On Rails,Json,Ajax,大家好,我正在尝试理解并用Ajax实现Rails动作控制器。我的问题是为什么在Ajax函数中无法获取Json数据并将其显示到console.log。我将ajax函数放在application.js文件中。我的ajaxget方法工作得很好,但post方法似乎不起作用。在文章索引页面中,当您单击“新建文章”时,它将呈现部分表单,ajax将与控制器中的创建操作通信,以便将数据附加到索引页面。但我无法将Json数据解析为Ajax post。 以下是我的代码文件: 更新图像 当我单击“仅在网络中创建jso

大家好,我正在尝试理解并用Ajax实现Rails动作控制器。我的问题是为什么在Ajax函数中无法获取Json数据并将其显示到console.log。我将ajax函数放在application.js文件中。我的ajaxget方法工作得很好,但post方法似乎不起作用。在文章索引页面中,当您单击“新建文章”时,它将呈现部分表单,ajax将与控制器中的创建操作通信,以便将数据附加到索引页面。但我无法将Json数据解析为Ajax post。 以下是我的代码文件: 更新图像 当我单击“仅在网络中创建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(){

        }
    });
});
$(函数(){
var$article_table=$(“#article_table”);
$.ajax({
键入:“GET”,
数据类型:“json”,
url:“/articles”,
成功:功能(文章){
$。每个(文章,功能(i,文章){
$article_table.append(“”+article.name+“”)
});
}
});
$('form#u article')。提交(函数(){
//var name=$('#article_name').val();
var name=JSON.parse(xhr.responseText);
$.ajax({
键入:“POST”,
url:“/articles”,
数据类型:“json”,
资料:姓名,,
成功:功能(数据){
//警报(data.id);
console.log('success',数据);
//调试器;
},
错误:函数(){
}
});
});
articles_controller.rb=>在create controller中,我将文章呈现为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
class-ArticlesController
_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 %>
<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 %>

禁止保存此文章:
index.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 %>
<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' %>");
$('new#article_link')。隐藏();

您需要像这样传递数据

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");
        }
    });
});

希望它有帮助

您需要像这样传递数据

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");
        }
    });
});


希望对您有所帮助

谢谢您的回复。我尝试过,但在console.log中仍然没有显示数据。请确保获取输入字段的值,如
alert(name);
I添加了alert(name);但是没有显示。我已经附加了问题中的图像。只有网络选项卡显示Json数据。我无法捕获该数据并将其显示在console.logHey@TranDuy中,请尝试以下
console.log(Json.stringify(data));
还是一样。console.log中没有显示任何内容。在console.log中我有“success”字符串,即使它没有捕获数据,但“success”字符串应该显示在console日志中,对吗?你认为success函数没有被调用吗?谢谢你的回复。我尝试过,但在console.log中仍然没有显示数据。请确保获得值输入字段,如
alert(name);
I添加了alert(name);但没有显示任何内容。我已经附加了问题中的图像。只有网络选项卡显示Json数据。我无法捕获该数据并在console.logHey@TranDuy中显示它,请尝试此
console.log(Json.stringify(data))
还是一样。在console.log中没有显示任何内容。在console.log中我有“success”字符串,即使它没有捕获数据,但“success”字符串应该显示在console log中,对吗?你认为success函数没有被调用吗?你确定一篇文章被保存了吗?也许你有错误?在js-f中为错误回调添加警报在
application.js
var name=JSON.parse(xhr.responseText);
Hi@kunashir.Yup文章在刷新页面时成功保存,我可以看到添加的新文章,但我需要捕获JSON数据,因为我想使用ajax(我不想刷新页面).ThanksHi@SRack。是的,我试过了,但没有成功。我想可能Ajax Post函数没有被调用,因为console.log中没有显示任何内容,即使我设置了“success”字符串。@TranDuy您在浏览器中看到服务器的响应了吗?您收到了什么?您确定保存了一篇文章吗?可能您有错误?在js-file中向错误回调添加警报。您在
application.js
的下一行中在哪里定义
xhr
var name=JSON.parse(xhr.responseText)
Hi@kunashir.Yup在刷新页面时成功保存了文章,我可以看到添加了新文章,但我需要捕获json数据,因为我想使用ajax(我不想刷新页面).ThanksHi@SRack。是的,我试过了,但没有成功。我想可能Ajax Post函数没有被调用,因为console.log中没有显示任何内容,甚至我在其中设置了“success”字符串。@TranDuy您在浏览器中看到服务器的响应了吗?您收到了什么?