0

我需要一些帮助来分析为什么以下简短的 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;

    });

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

4

1 回答 1

0

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

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'https://website.com/a/login',
            data: data,
            dataType: 'json'
于 2012-01-02T21:27:17.977 回答