【问题标题】:How to pass blank array in ajax request?如何在ajax请求中传递空白数组?
【发布时间】:2019-01-04 11:06:16
【问题描述】:

我面临一个问题,即我无法在 Ajax Post 请求中传递空白数组(如果数组为 null),尽管在第一步中初始化了数组。在 post 请求中传递非空数组。

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

(例如 ["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){}
});

});

【问题讨论】:

    标签: javascript php jquery arrays ajax


    【解决方案1】:

    试试这个:

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

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

    【讨论】:

      【解决方案2】:

      如果您在 service_locations 中未选择任何值,则 selectedDeliveryLocations = $("select[name='service_locations[]']").val(); 返回 undefined 或 null。

      您可以将默认值作为空数组传递以覆盖错误值,如下所示

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

      【讨论】:

        猜你喜欢
        • 2012-07-12
        • 2022-10-05
        • 2012-02-12
        • 1970-01-01
        • 2018-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-26
        相关资源
        最近更新 更多