javascript - 如何在ajax请求中传递空白数组?

标签 javascript php jquery arrays ajax

我遇到一个问题,尽管在第一步中初始化了数组,但我无法在 Ajax Post 请求中传递空白数组(如果数组为 null)。在 post 请求中传递的不是空数组。

在下面的代码中,我初始化了名为selectedDeliveryLocations数组。当数组不为空时

(for eg. ["888888", "17", "5", "2", "3"])

我在ajax页面上收到的变量selectedDeliveryLocations,但如果它是空的,我只收到Ajax请求上的城市变量,我应该收到selectedDeliveryLocations变量以及selectedDeliveryLocations []空白数组。

$("select[name='city']").on("change", function(){
var city = $(this).val();

var selectedDeliveryLocations = [];
if( $("select[name='service_locations[]']").val() != '' && $("select[name='service_locations[]']").val() != null){
    selectedDeliveryLocations = $("select[name='service_locations[]']").val();
}

$.ajax({
    url:"ajaxGetSelectedDeliveryLocOnCityChange.php",
    data:{
            city:city,
            selectedDeliveryLocations:selectedDeliveryLocations
        },
    type:"post",
    success: function(response){
        var response = JSON.parse(response);
        if(response){

            $("select[name='service_locations[]']").html(response.responseContent);
            $("select[name='service_locations[]']").selectpicker("refresh");

            showSelectedDeliveryLocations();
        }
    },
    error: function(){ alert("Something went wrong, please try again"); },
    complete: function(response){}
});

});

最佳答案

试试这个:

selectedDeliveryLocations = $("select[name='service_locations[]']").val() || '';

并在您的服务器端进行相应的检查。

关于javascript - 如何在ajax请求中传递空白数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54037764/

相关文章:

javascript - 每次将类添加到元素时,使用 waitForKeyElements 显示一条消息

javascript - 如何在每次旋转后显示旋转结果

javascript - 如何在 CSS 和 Jquery 上设置 float 位置弹出消息

javascript - 我如何自动执行javascript?

javascript - 有没有办法用 CasperJS 截取新遗物的仪表板屏幕截图?

php - PDO INSERT 查询 500 服务器错误

php - 如何比较string或int类型?

php - MS SQL Studio .bak 到 PHPmyAdmin

javascript - jQuery (...).validate 不是一个函数

javascript - 窗口重定向困惑