我正試圖學習如何從我的rails 3.2.2項目異步獲取數據。我對javascript和jquery都很陌生,但我瞭解到,javascript無法從不同域中的服務器獲取數據。爲了避免使用$ .ajax(),$ getJSON()和/或$ .jsonp(),所以我的第一個問題是什麼時候應該使用另一個?我有一個簡單的腳手架組成的一個控制器=>圖像和一個字段=> t.string: 。名字
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
我首先要探討的索引操作,並使用$阿賈克斯()調用在up.html「GET」圖像名稱的列表:
<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 <
我迷路了。我不確定我是否應該使用'?callback =?'在我的網址,或者如果我應該在我的控制器或其他什麼其他的參數完全?
關於您在控制檯中看到的第一個警告訊息,請參閱http://stackoverflow.com/問題/ 7825448/webkit-issues-with-event-layerx-and-event-layery – Matt 2012-04-19 15:53:12