【发布时间】:2015-12-03 13:11:09
【问题描述】:
辛纳特拉的路线:
post '/favorite' do
response['Access-Control-Allow-Origin'] = '*'
p response
end
JS:
注意:这还不是全部,它是相关的部分。它省略了收藏电影的创建方式,但我保证,当我在控制台记录它时,它会返回预期的内容,如下所述
window.onload = function(){
var myApp = new App;
myApp.addEventListenerToFavoriteButton();
};
var App = function(){
this.myMovies = null
};
App.prototype.addEventListenerToFavoriteButton = function(){
var self = this;
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.tagName.toLowerCase() === 'button'){
self.favorite(event.target.id);
}
});
};
App.prototype.favorite = function(movieID){
var favoritedMovie = this.myMovies.movies[movieID]
console.log(JSON.stringify(favoritedMovie)) // {title":"Yo soy Betty la fea","year":"1999–2001","imdbID":"tt0233127","html":"<h2>Yo soy Betty, la fea</h2><h3>1999–2001</h3><br><button id='0'>favorite</button>"}
var url = "http://localhost:4567/favorite";
var xhr = new XMLHttpRequest();
xhr.open('POST', encodeURI(url), true);
xhr.setRequestHeader("content-type",'application/json');
xhr.onload = function() {
if (xhr.status === 200 ) {
console.log('tentative success!' + xhr.responseText); // tentative success!
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(JSON.stringify(favoritedMovie));
}
var Movie = function(movieObject, index){
this.title = movieObject['Title'],
this.year = movieObject['Year'],
this.imdbID = movieObject['imdbID']
this.html = "<h2>" + this.title + "</h2><h3>" + this.year + "</h3><br><button id='" + index + "'>favorite</button>"
}
Sinatra 控制台中的响应:
= Sinatra (v1.4.6) has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.5.0 codename Knife)
>> Maximum connections set to 1024
>> Listening on localhost:4567, CTRL+C to stop
#<Sinatra::Response:0x007f803b9061c8 @status=200, @header={"Content-Type"=>nil, "Access-Control-Allow-Origin"=>"*"}, @chunked=false, @writer=#<Proc:0x007f803b905ea8@/Users/awhit012/.rvm/gems/ruby-2.1.2/gems/rack-1.6.4/lib/rack/response.rb:30 (lambda)>, @block=nil, @length=0, @body=[]>
127.0.0.1 - - [07/Sep/2015:17:34:17 -0700] "POST /favorite HTTP/1.1" 200 - 0.0102
我试过添加
content_type :json
到路线。这有一个区别:
@header={"Content-Type"=>"application/json", "Access-Control-Allow-Origin"=>"*"}
这对我来说似乎更好,但身体仍然是空的。
【问题讨论】:
-
我你的源代码在哪里?
-
源代码和你这里贴的代码不对应,所以有点混乱。你的问题也令人困惑。我认为您将
Sinatra::Request与Sinatra::Response混淆了。Sinatra::Request对象包含您的xhr对象在 Javascript 代码中发送的查询,Sinatra::Response对象是您的路由将发送回 Javascript 代码的内容(并将由xhr.onload接收)。 -
天哪,谢谢。我把那两个弄混了。抱歉,这令人困惑。那是因为我很困惑。去搞清楚。我将在今天晚些时候发布解决方案。
标签: javascript xml api post sinatra