在发送之前在我的 ajax url 末尾添加一个字符串

发布于 2025-01-16 08:10:57 字数 3371 浏览 0 评论 0原文

我不知道为什么我不能让它工作。我有一个通过 Ajax 获取对象的代码:

这是我的代码:


var $form = $(document).find('#my_form');
const $objectassemblepoint = $('#my_object_assemble_point');

     function convertFromDataToArray(formData) {
            let data = [];
            formData.forEach(function (obj) {
                if (obj.value) {
                    // break with price
                    if (['min_price', 'max_price'].includes(obj.name)) {
                        const dataValue = $form.find('input[name=' + obj.name +']').data(obj.name.substring(0, 3));
                        if (dataValue == parseInt(obj.value)) {
                            return;
                        }
                    }
                    data.push(obj);
                }
            });
            return data;
        }

     if ($form.length) {
            $(document).on('submit', '#my_form', function (event) {
                event.preventDefault();
                const $form = $(event.currentTarget);
                const formData = $form.serializeArray();
                let data = convertFromDataToArray(formData);
                let uriData = [];

                const $elPage = $objectassemblepoint.find('input[name=page]');
                if ($elPage.val()) {
                    data.push({name: 'page', value: $elPage.val()});
                }

                data.map(function (obj) {
                    uriData.push(encodeURIComponent(obj.name) + '=' + obj.value);
                });

                var popStateUrl = $form.attr('action') + (uriData && uriData.length ? ('?' + uriData.join('&')) : '');

                var addThisToEnd = '&q=luxury';

                $.ajax({
                    url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                    type: 'GET',
                    data: data,
                    beforeSend: function () {
                        //Do stuffs before send
                    },
                    success: function (response) {
                        if (response.error === false) {
                            $objectstoadd.html(response.data);
                            
                            if (popStateUrl !== window.location.href) {
                                window.history.pushState(data, response.message, popStateUrl);
                            }
                        } else {
                            showError(response.message || 'Something went wrong!');
                        }
                    },
                    error: function (response) {
                        handleError(response);
                    },
                    complete: function () {
                        //Some things to do
                    }
                });
         }

使用上面的代码,当用户选择一种慢跑鞋时,来自 Ajax 的 url 变为:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype%5B%5D=1&_=[TIMESTAMP]

但我想要这样的东西:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype%5B%5D=1&q=luxury&_=[TIMESTAMP]

我已经尝试过这样做:

$.ajax({
                    url: $form.attr('action')+addThisToEnd // Since I have a variable with the string as above,

但一切变得混乱。拜托,我对 Ajax 不太了解。请帮忙。

I don't know why I can't get this to work. I have a code to GET objects via Ajax:

Here is my code:


var $form = $(document).find('#my_form');
const $objectassemblepoint = $('#my_object_assemble_point');

     function convertFromDataToArray(formData) {
            let data = [];
            formData.forEach(function (obj) {
                if (obj.value) {
                    // break with price
                    if (['min_price', 'max_price'].includes(obj.name)) {
                        const dataValue = $form.find('input[name=' + obj.name +']').data(obj.name.substring(0, 3));
                        if (dataValue == parseInt(obj.value)) {
                            return;
                        }
                    }
                    data.push(obj);
                }
            });
            return data;
        }

     if ($form.length) {
            $(document).on('submit', '#my_form', function (event) {
                event.preventDefault();
                const $form = $(event.currentTarget);
                const formData = $form.serializeArray();
                let data = convertFromDataToArray(formData);
                let uriData = [];

                const $elPage = $objectassemblepoint.find('input[name=page]');
                if ($elPage.val()) {
                    data.push({name: 'page', value: $elPage.val()});
                }

                data.map(function (obj) {
                    uriData.push(encodeURIComponent(obj.name) + '=' + obj.value);
                });

                var popStateUrl = $form.attr('action') + (uriData && uriData.length ? ('?' + uriData.join('&')) : '');

                var addThisToEnd = '&q=luxury';

                $.ajax({
                    url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                    type: 'GET',
                    data: data,
                    beforeSend: function () {
                        //Do stuffs before send
                    },
                    success: function (response) {
                        if (response.error === false) {
                            $objectstoadd.html(response.data);
                            
                            if (popStateUrl !== window.location.href) {
                                window.history.pushState(data, response.message, popStateUrl);
                            }
                        } else {
                            showError(response.message || 'Something went wrong!');
                        }
                    },
                    error: function (response) {
                        handleError(response);
                    },
                    complete: function () {
                        //Some things to do
                    }
                });
         }

With the above code, when the user selects a type of joggeres, the url from Ajax becomes:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype%5B%5D=1&_=[TIMESTAMP]

But I desire something like this rather:

https://mydomainname.com/joggers?min_price=0&max_price=100&thetype%5B%5D=1&q=luxury&_=[TIMESTAMP]

I have tried doing:

$.ajax({
                    url: $form.attr('action')+addThisToEnd // Since I have a variable with the string as above,

But everything gets messy. Please I do not know much of Ajax. Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜无邪 2025-01-23 08:10:57

您没有提供完整的脚本来理解您的问题,但是如果您忘记了脚本中的某些内容,它会显示您:

编辑:函数convertFromDataToArray您不需要它,因为数据已经是数组

    var $form = $(document).find('#my_form');
    const $objectassemblepoint = $('#my_object_assemble_point');

    if ($form.length) {
        $(document).on('submit', '#my_form', function (event) {
            event.preventDefault();
            const $form = $(event.currentTarget);
            const data = $form.serializeArray();
            let uriData = [];

            const $elPage = $objectassemblepoint.find('input[name=page]');
            if ($elPage.val()) {
                data.push({ name: 'page', value: $elPage.val() });
            }

            data.map(function (obj) {
                uriData.push(encodeURIComponent(obj.name) + '=' + obj.value);
            });

            var popStateUrl = $form.attr('action') + (uriData && uriData.length ? ('?' + uriData.join('&')) : '');


            var addThisToEnd = {name: 'q', value:'luxury'};
            data.push(addThisToEnd);

            console.log($form.attr('action') + '?' + $.param(data));


            $.ajax({
                url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                type: 'GET',
                data: data,
                beforeSend: function () {
                    //Do stuffs before send
                },
                success: function (response) {
                    if (response.error === false) {
                        $objectstoadd.html(response.data);

                        if (popStateUrl !== window.location.href) {
                            window.history.pushState(data, response.message, popStateUrl);
                        }
                    } else {
                        showError(response.message || 'Something went wrong!');
                    }
                },
                error: function (response) {
                    //handleError(response);
                },
                complete: function () {
                    //Some things to do
                }
            });
        });
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form" action="https://yourdomain.com/joggers">
        Min price: <input type="text" name="min_price" value="20"><br>
        Max price: <input type="text" name="max_price" value="100"><br>
        The Type: <input type="text" name="thetype" value="test"><br>
        <button type="submit">Submit</button>
    </form>

You don't provided your full script to understand your problem, but this It will show you if you forgot something in your script:

Edit: Function convertFromDataToArray you don't need it cause data is already is array

    var $form = $(document).find('#my_form');
    const $objectassemblepoint = $('#my_object_assemble_point');

    if ($form.length) {
        $(document).on('submit', '#my_form', function (event) {
            event.preventDefault();
            const $form = $(event.currentTarget);
            const data = $form.serializeArray();
            let uriData = [];

            const $elPage = $objectassemblepoint.find('input[name=page]');
            if ($elPage.val()) {
                data.push({ name: 'page', value: $elPage.val() });
            }

            data.map(function (obj) {
                uriData.push(encodeURIComponent(obj.name) + '=' + obj.value);
            });

            var popStateUrl = $form.attr('action') + (uriData && uriData.length ? ('?' + uriData.join('&')) : '');


            var addThisToEnd = {name: 'q', value:'luxury'};
            data.push(addThisToEnd);

            console.log($form.attr('action') + '?' + $.param(data));


            $.ajax({
                url: $form.attr('action'), // Plainly: "https://mydomainname.com/joggers" from my actual form
                type: 'GET',
                data: data,
                beforeSend: function () {
                    //Do stuffs before send
                },
                success: function (response) {
                    if (response.error === false) {
                        $objectstoadd.html(response.data);

                        if (popStateUrl !== window.location.href) {
                            window.history.pushState(data, response.message, popStateUrl);
                        }
                    } else {
                        showError(response.message || 'Something went wrong!');
                    }
                },
                error: function (response) {
                    //handleError(response);
                },
                complete: function () {
                    //Some things to do
                }
            });
        });
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form" action="https://yourdomain.com/joggers">
        Min price: <input type="text" name="min_price" value="20"><br>
        Max price: <input type="text" name="max_price" value="100"><br>
        The Type: <input type="text" name="thetype" value="test"><br>
        <button type="submit">Submit</button>
    </form>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文