我想知道是否有人有使用Sammy.js的经验,有一个使用跨源资源共享的解决方案?
编辑
最初的问题基本上只是问人们可能使用什么方法来使用Sammy.js来完成CORS,比如反编译.load()方法之类的。
我遇到的问题是,当使用.load()方法时,当尝试与位于不同域(CORS启用的Sinatra应用程序)的sinatra交互时,事情并不像预期的那样工作。
如果我使用Ajax调用,如:
this.get('#/', function(context) {
$.ajax({
url: 'http://localhost:4567/posts', //located on other domain
dataType: 'json',
success: function(items) {
$.each(items, function(i, item) {
context.log(item.title);
});
}
});
});..。firebug显示控制台中的项/帖子,但如果我使用.load,如下所示:
this.load('http://localhost:4567/posts')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item.title);
});
});..。一切都不是很好,firebug控制台显示了http://pastie.org/4051256,尽管firebug也表示已成功检索到json的posts数组。
如果我尝试在模板中呈现条目而不是日志记录,则也会发生这种行为:
this.load('http://localhost:4567/posts')
.then(function(items) {
$.each(items, function(i, item) {
context.render('tmpl/item.mustache', {item: item})
.appendTo(context.$element());
});
});..。请记住,返回是一个只包含三个帖子的json数组,模板正在成功加载,但没有注入任何数据,并且它被呈现的次数与上面所示的“未定义”行数相同:(
编辑2
.load方法在sammy.js中如何对待此调用与jquery调用不同?
或
为何会出现上述问题?
发布于 2012-08-07 00:52:24
您需要向请求中添加预期的响应类型。否则,响应将作为字符串导入,同时看起来像Firebug中的数组/对象。您的标准jQuery方法可以工作,因为您已经这样做了:
dataType: 'json',使用.load()方法,可以如下所示指定预期的响应类型:
this.load('http://localhost:4567/posts', {dataType: 'json'})或者像这样:
this.load('http://localhost:4567/posts', {json: true})如果资源的URL中有" JSON“的名称,sammy.js将自动将预期的响应类型设置为JSON。这也是为什么sammy.js网站上的示例有效的原因。
https://stackoverflow.com/questions/10936797
复制相似问题