【问题标题】:AJAX request not working while working on POSTMAN在使用 POSTMAN 时 AJAX 请求不起作用
【发布时间】:2021-11-29 14:27:44
【问题描述】:

我对 API 和 AJAX 很陌生,在这里遇到了问题。我在 PHP (Symfony) 中创建了一个端点。

当我使用 Postman 在此端点上调用 GET 时,我得到了正确的答案。

但是当我尝试使用 AJAX 获得答案时,我收到了 500 错误。 这是我的代码:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
            crossorigin="anonymous"></script>
    <button id="testButton">TEST</button>
    <script>
        $('#testButton').click(function (e) {

            let week = 42;
            let year = 2021;
            let data = JSON.stringify({
                id:1,
                week: week,
                year: year}
            );
            $.ajax({
                url: '{{ path('bookings')}}',
                type: 'GET',
                contentType: "application/json",
                dataType: 'json',
                data: data,
                success: function (data, status) {
                    console.log(status)
                    if (status === 'success') {
                        console.log(data);
                        console.log('success');
                    } else {
                        console.log('failure');
                    }
                }
            });
        });
    </script>

Path(bookings) 返回 127.0.0.1:8000/bookings。

我得到的错误是:

请您指出我在哪里犯了错误,好吗?

【问题讨论】:

  • 请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中。 How to Ask

标签: php json ajax postman


【解决方案1】:

当您使用 jQuery 发送 GET 请求时,您可以将 data 属性作为 PlainObject 传递

不使用 stringify 试试这个:

let data = {
   id:1,
   week: week,
   year: year
};

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 2019-12-05
    • 2018-11-04
    • 2017-09-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多