在将关联数组从javascript传递到php时遇到麻烦

trouble passing associative array from javascript to php

本文关键字:php 遇到 麻烦 关联 数组 javascript      更新时间:2023-09-26

我正在使用CodeIgniter开发一个应用程序。我在javascript中创建了一个associative array,并通过ajax将值传递给php脚本。在javascript中,只有当两个文本字段不为空时,才会将值插入数组。当我将一个空数组传递给php脚本并回显模型中的变量时,我得到的输出为

array([0]=> ) 

如果我通过插入值传递数组模型的响应是

array(['key1']=>['value1'])  

如何避免[0] ?我的脚本是

if(document.getElementById("insertname").value != null &&    document.getElementById("insertnumber").value != null)
{var partner_name = new Object();
 partner_name[document.getElementById("insertname").value] = document.getElementById("insertnumber").value;
}
$.ajax({
          type:"POST",
          url:"",
          data:{Partner_name:partner_name,cus_id:id,cus_message:customermessage},
          success:function(responsee){
            alert("Message Sent and Stored");
            alert(responsee);
          }
        });

var dump value

array(1) {
  [0]=>
  string(0) ""
}

为什么不这样做:

<script type="text/javascript">
<?php if(count($array) > 0){ ?>
var _array = "<?php $array; ?>"; //put here what you need this is just an example
<?php }else{ ?>
var _array = "";
<?php } ?>
</script>

try

var data = {
    'one' : {
       'child' : '',
    },
    'two' : '',
}
$.ajax({ data : data });