首页 > 解决方案 > 如果在 beforeSend 中修改了 URL,jQuery $.ajax 数据会丢失。为什么?

问题描述

我有一个使用 jQuery 的 ajax 调用,它将有一个基于input select.

这是我的代码:

            $.ajax({
                dataType: 'json',
                data: {csrf: wpApiSettings.nonce},
                beforeSend: function (xhr, settings) {
                    if (addressType === 'sender') {
                        this.url = '/api/private/autocomplete/sender-countries/';
                    } else if (addressType === 'destination') {
                        this.url = '/api/private/autocomplete/destination-countries/';
                    } else {
                        xhr.abort();
                    }
                },
                success: function (response) {
                    if (response.success) callback(response.data);
                }
            });

我尝试了很多事情,但是如果 beforeSend 中的条件之一为真并且 URL 被修改,请求数据总是会被删除。我通过声明一个 URL 发现了这一点,就像您通常在 ajax 函数中所做的那样。如果从未满足 beforeSend 条件,则发送带有 nonce 的数据。如果在 beforeSend 中修改了 url,则不会向服务器发送带有 nonce 的数据。

有人可以帮我解决这个问题吗?在 beforeSend 中重新声明数据听起来很奇怪,为什么这首先不起作用?

标签: jquery

解决方案


您没有指定method: 'POST',因此默认情况下会发送一个 GET 请求。GET 请求的参数附加到 URL。

这是在beforeSend调用函数之前完成的,所以如果它修改了 URL,这个连接就会丢失。

因此,如果您要在 中自定义 URL,则beforeSend需要自己附加参数。

$.ajax({
    dataType: 'json',
    data: {csrf: wpApiSettings.nonce},
    beforeSend: function (xhr, settings) {
        if (addressType === 'sender') {
            settings.url = '/api/private/autocomplete/sender-countries/?' + $.param(settings.data);
        } else if (addressType === 'destination') {
            settings.url = '/api/private/autocomplete/destination-countries/?' + $.param(settings.data);
        } else {
            xhr.abort();
        }
    },
    success: function (response) {
        if (response.success) callback(response.data);
    }
});

但更简单的解决方案是将条件移到调用之外。

if (address_type === 'sender' || address_type = 'destination') {
    $.ajax({
        url: `/api/private/autocomplete/${address_type}-countries/`,
        dataType: 'json',
        data: {csrf: wpApiSettings.nonce},
        success: function (response) {
            if (response.success) callback(response.data);
        }
    });
}

推荐阅读