1

我正在尝试使用下面的代码将数据发布到http://requestb.in/。但是,我继续收到 HTTP/1.1 404 Not Found。我只是想在下面的代码中查看我的数据的 JSON 格式。

感谢您提供任何可能使我找到解决方案的想法。我正在使用 Fiddler 来定位我在第一段中提到的错误。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostJSON.aspx.cs" Inherits="SimpleJSONPost.PostJSON" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>    
<script type="text/javascript">    
    $(document).ready(function () {
        $("#button1").click(function () {
            $.ajax({
                type: "POST",
                url: "http://requestb.in/1g8nene1",
                contentType: "application/json; charset=utf-8",
                data: JSON.Stringify({"name": "John"}),
                dataType: "json",
                success: function (msg) { alert("Post Succeeded: " + msg) },
                error: function (msg) { alert("Post Failed: " + msg) }
            });
        });
    });    
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="button1" runat="server" Text="PostJSON" />
    </div>
    </form>
</body>
</html>
4

2 回答 2

4

可能出现的问题:

  1. 404 可能是因为 RequestBin 使 URL 过期,而您的 URL 可能已过期。

  2. 另一个问题可能是 JavaScript,它是JSON.stringify而不是JSON.Stringify.

  3. RequestBin 返回text/plain并且您正在使用dataType: "json". 您应该使用dataType: "text"RequestBin 进行测试。

  4. RequestBin 不允许 CORS 导致:XMLHttpRequest 无法加载“...”请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin '...' 不允许访问。

即使您“修复” 1、2 和 3,第 4 项也不会让它起作用。

一个可能的解决方案是使用PutsReq,它允许 CORS 并且您可以将响应配置为有效的 JSON。

示例 PustReq 响应生成器:

response.status = 200;
response.headers['Content-Type'] = 'application/json';
response.body = { 'msg': 'ok' };

您的 Ajax 调用(将YOUR-TOKEN替换为有效的 PutsReq 令牌):

$.ajax({
    type: "POST",
    url: "https://putsreq.herokuapp.com/<YOUR-TOKEN>",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ "name": "John" }),
    dataType: "json",
    success: function (msg) { alert("Post Succeeded: " + msg) },
    error: function (msg) { alert("Post Failed: " + msg) }
});
于 2014-05-08T02:24:57.163 回答
0

我不知道这是否与您的问题有关,但是您为什么要“字符串化”您发送的数据?

$.ajax({ type: "POST", url: "http://requestb.in/1g8nene1", contentType: "application/json; charset=utf-8", data: {"name": "John"} , dataType: "json", success: function (msg) { alert("Post Succeeded: " + msg) }, error: function (msg) { alert("Post Failed: " + msg) } });

将它作为一个普通对象发送,jQuery 会处理一切。我已经在本地测试中对其进行了更改以查看您的问题,并且响应状态对我来说是 200。

于 2012-04-16T18:57:42.723 回答