在 rails 3.2.2 中使用 $.ajax() 异步获取数据

Obtaining data asynchronously using $.ajax() in rails 3.2.2

本文关键字:异步 ajax 获取 数据 rails      更新时间:2023-09-26

我正在尝试学习如何从我的 rails 3.2.2 项目中异步"获取"数据。 我是javascript和jquery的新手,但我知道javascript不能从不同域中的服务器获取数据。 为了解决这个问题,我已经读到了使用 $.ajax()、$getJSON() 和/或 $.jsonp() 的信息,所以我的第一个问题是什么时候应该使用一个而不是另一个?

我正在尝试在我的 rails 3.2.2 项目中使用一种技术(例如 $.ajax()。我有一个简单的脚手架,由一个控制器 => 图像和一个字段 => t.string:name 组成。

class ImagesController < ApplicationController
  # GET /images
  # GET /images.json
  def index
    @images = Image.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @images }
    end
  end
  # GET /images/1
  # GET /images/1.json 
  def show
    @image = Image.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @image }
    end
  end
  # GET /images/new
  # GET /images/new.json
  def new
    @image = Image.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @image }
    end
  end
  # GET /images/1/edit
  def edit
    @image = Image.find(params[:id])
  end
  # POST /images
  # POST /images.json
  def create
    @image = Image.new(params[:image])
    respond_to do |format|
      if @image.save
        format.html { redirect_to @image, notice: 'Image was successfully created.' }
        format.json { render json: @image, status: :created, location: @image }
      else
        format.html { render action: "new" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end
  # PUT /images/1
  # PUT /images/1.json
  def update
    @image = Image.find(params[:id])
    respond_to do |format|
      if @image.update_attributes(params[:image])
        format.html { redirect_to @image, notice: 'Image was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end
  # DELETE /images/1
  # DELETE /images/1.json
  def destroy
    @image = Image.find(params[:id])
    @image.destroy
    respond_to do |format|
      format.html { redirect_to images_url }
      format.json { head :no_content }
    end
  end
end

我首先想探索索引操作并使用 $.ajax() 调用 up.html 来"获取"图像名称列表:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">    </script>
</head>
<body>
    <script>
        $(document).ready( function (){ 
            $("button").click(function(){
                    $.ajax({
                        dataType: 'jsonp',
                        url: "http://localhost:3000/images",
                        success: function(response) {
                            console.log(response);
                        }
                    });
            });
        });
    </script>
    <button id ="button" type ="button">Get names</button>
</body>
</html>

我从控制台收到以下内容:

event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed  from the engine in the near future.
jquery.min.js:16Resource interpreted as Script but transferred with MIME type text/html:  "http://localhost:3000/images?    callback=jQuery15209319186636712402_1334849479698&_=1334849481034".
images:1Uncaught SyntaxError: Unexpected token <

我迷路了。我不确定我是否应该在我的 url 中使用"?callback=?",或者我是否应该在我的控制器中拥有其他参数或完全其他参数?

       $(document).ready( function (){ 
            $("button").click(function(){
                    $.ajax({
                        dataType: 'json',  // not jsonp
                        url: "http://localhost:3000/images.json",
                        success: function(response) {
                            console.log(response);
                        }
                    });
            });
        });

忽略控制台中的第一行 - 这是最近Chrome/jquery版本中出现的标准警告。

第二行告诉你你的 Web 应用发送了 html,而不是 json

第三行是由于试图解析html(大概以" <html...开头")就好像它是一个json字符串一样。

所以,你需要告诉rails给你发送json,而不是html。 尝试将 json 调用中的 url 更改为"http://localhost:3000/images.json"。