jQuery ajax。未使用Sinatra JSON响应调用
我将回到一个简单的Sinatra项目,但在执行jQuery.done()块时遇到了一个小问题 背景: -本地开发机器(目前)-MacOSX小牛 -Apache/mysql/PHP堆栈在808888上运行和侦听 -sinatra在3000上运行 Sinatra的装卸工已被剥离至最低限度:jQuery ajax。未使用Sinatra JSON响应调用,jquery,ruby,ajax,json,sinatra,Jquery,Ruby,Ajax,Json,Sinatra,我将回到一个简单的Sinatra项目,但在执行jQuery.done()块时遇到了一个小问题 背景: -本地开发机器(目前)-MacOSX小牛 -Apache/mysql/PHP堆栈在808888上运行和侦听 -sinatra在3000上运行 Sinatra的装卸工已被剥离至最低限度: post '/' do status 200 content_type :json params.to_json end 提交的表格: <form action="http:/
post '/' do
status 200
content_type :json
params.to_json
end
提交的表格:
<form action="http://localhost:3000/ph/api" method="post" id="apitest">
<input type="hidden" name="recipes[]" value="cornbread"/>
<input type="hidden" name="recipes[]" value="taters"/>
<input type="hidden" name="recipes[]" value="PO-TAY-TOES"/>
<input type="submit"/>
</form>
当我单击时,表单提交。从查尔斯的交通状况来看,一切都是合法的
请求如下:
POST / HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: text/plain, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/apitest.html
Content-Length: 70
Origin: http://localhost
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
recipes%5B%5D=cornbread&recipes%5B%5D=taters&recipes%5B%5D=PO-TAY-TOES
以下是回应:
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Content-Length: 48
X-Content-Type-Options: nosniff
Connection: keep-alive
Server: thin 1.6.1 codename Death Proof
{"recipes":["cornbread","taters","PO-TAY-TOES"]}
正如最后所料,我的“始终”处理程序将启动。“完成”似乎永远不会开火。我想这里有一些安全问题(同源?)让我无法理解,但我已经关注这个问题很久了,以至于我被炒了,或者错过了一些非常明显的东西
非常感谢您提供的任何见解或提示
添加的fail()块如下所示:
myreq.fail(function(xhr, status, err) {
console.log(xhr.status + " - " + xhr.statusText);
});
控制台的输出:
0 - error
Status&err分别不提供任何信息和“error”。如果您使用的是json
var myreq = $.ajax({
type:"POST",
url:"http://localhost:3000/",
dataType:"json",
data:{"vl":$('#apitest').serialize()}
});
myreq.done(function (response, textStatus, jqXHR){
alert("done");
});
// callback handler that will be called on failure
myreq.fail(function (jqXHR, textStatus, errorThrown){
alert("errors"+textStatus);
});
myreq.always(function() {
alert("always");
});
provided http://localhost:3000/ should return a valid json back.
最终,通过direct AJAX处理这个问题是一件很糟糕的事情——从来没有弄清楚到底发生了什么。在服务器上使用一个粗糙的中介使一切都很顺利。尝试添加一个失败处理程序,看看是否会触发,以及有哪些错误。失败会给我一个状态0和一条消息“error”,并查看对象的responseText为“”。使用最新版本的jQuery,它仍然会失败吗?使用jQuery 1.10.2。无法使用2.x,因为不幸的是需要IE8支持。
var myreq = $.ajax({
type:"POST",
url:"http://localhost:3000/",
dataType:"json",
data:{"vl":$('#apitest').serialize()}
});
myreq.done(function (response, textStatus, jqXHR){
alert("done");
});
// callback handler that will be called on failure
myreq.fail(function (jqXHR, textStatus, errorThrown){
alert("errors"+textStatus);
});
myreq.always(function() {
alert("always");
});
provided http://localhost:3000/ should return a valid json back.