我有一个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被修改,请求数据总是会被删除。我像在ajax函数中一样声明了一个URL,从而发现了这一点。如果从未满足beforeSend条件,则发送带有现时值的数据。如果在beforeSend中修改url,则不会将带有nonce的数据发送到服务器。
有人能帮我解决这个问题吗?在beforeSend中重新声明数据听起来很奇怪,为什么这在一开始就不起作用?
发布于 2021-07-15 06:47:56
您没有指定method: 'POST',所以默认情况下这会发送一个GET请求。GET请求的参数将追加到URL中。
这是在调用beforeSend函数之前完成的,所以如果它修改了URL,这个连接就会丢失。
因此,如果您要在beforeSend中自定义URL,则需要自己添加参数。
$.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);
}
});
}https://stackoverflow.com/questions/68385742
复制相似问题