jQuery ajax .done 不使用 Sinatra JSON 响应调用



我正在通过一个简单的Sinatra项目回到东西上,但是我在执行jQuery .done()块时遇到了一个小问题。

背景:- 本地开发机器(目前) - Mac OS X 特立独行- Apache/mysql/PHP 堆栈在 80、8888 上运行和监听- 辛纳屈运行在3000

Sinatra中的处理程序已被剥离到最低限度:

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>

带有jQuery的AJAX(1.10,谷歌托管):

$('#apitest').submit(function(event) {
    event.preventDefault();
    var myreq = $.ajax({
        type:"POST",
        url:"http://localhost:3000/",
        dataType:"text",
        data:$('#apitest').serialize()
    });
    myreq.done(function() {
        alert("done");
    });
    myreq.always(function() {
        alert("always");
    });
});

当我单击时,表单提交。看看查尔斯的交通,一切看起来都是合法的。

以下是请求:

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
状态和错误

分别不给出任何内容和"错误"。

如果您使用的是 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. 

归根结底,通过直接 AJAX 处理这个问题是一团糟 - 从来没有弄清楚发生了什么。在服务器上使用粗糙的中介使一切顺利进行。

最新更新