【问题标题】:jquery ajax call giving error, in conjunction with RESTful APIjquery ajax 调用给出错误,结合 RESTful API
【发布时间】:2012-01-02 21:18:47
【问题描述】:

我需要一些帮助来分析为什么以下简短的 jquery 代码不起作用。 ajax 调用基于 RESTful API,我已经确认这个确切的调用可以正常工作。所以不存在后端问题。我只关心这里的前端,我缺乏经验。我认为以下应该相当简单,我看不出是什么导致 ajax 出错。有什么明显的错误吗?

<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#submit").click(function () {
                var data = {};
                data["login_name"] = $("#login_name")[0].value;
                data["password"] = $("#password")[0].value;

                $.ajax({
                    type: "POST",
                    url: "https://website.com/a/login",
                    data: data,
                    dataType: "json"
                }).success(function (data) {
                    $("#output")[0].value = JSON.stringify(data, null, "\t");
                }).error(function (a, b, c) {
                    $("#output")[0].value = alert(JSON.stringify(c, null, "\t"));
                });
                $("#output")[0].value = "Sending...";
            });
        });
    </script>
</head>
<body>
    <span class="value">
        <input type="text" class="value" id="login_name" style="width:350px" />
    </span>
    <span class="value">
        <input type="text" class="value" id="password" style="width:350px" />
    </span>
    <span>
        <input type="button" id="submit" value="Send Request" />
    </span>
    <textarea id="output" readonly="readonly"></textarea>
</body>

我只能怀疑数据有问题。我通过修改一些现有代码创建了上面的代码:

var data = {};

    $("#fields div.entry").each(function(i,elem) {

        elem = $(elem);

        data[elem.find("input.field")[0].value]=elem.find("input.value")[0].value;

    });

上面的代码是在创建数据的原始工作代码中,我看不出它与我创建的数据数组有什么不同......

【问题讨论】:

  • 这个api和你的页面在同一个域吗?
  • @rejj 不,不是!我也刚刚意识到这一点。当原始页面不在同一个域中时,它也不会工作。我该如何解决?我需要此代码才能在 phonegap 中工作。
  • 只能使用jsonp,需要服务器端配合

标签: jquery restful-url


【解决方案1】:

作为一个快速的猜测,您可以尝试将内容类型添加到帖子中:

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'https://website.com/a/login',
            data: data,
            dataType: 'json'

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多