php - 将数组作为一个变量从 JavaScript 发送到 PHP

标签 php javascript jquery submit form-submit

我有一个表单,URL是这样的:

http://hostname/projectname/classname/methodname/variablename

在我的 JavaScript 中,我填充了一个这样的数组:

var currentrelations = new Array();
    $(".ioAddRelation").each(function(index) {
        currentrelations[index] = $(this).html();
    });

这个数组有两个值['eeeeee','eeeeee']

所以网址是:

http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee

在我的 PHP 中,在 InformationObject 类中的 addIO 方法上:

public function addIO($currentRelations =null) {
        $name = $_POST['name'];
        $type = $_POST['type'];
        $concept = $_POST['concept'];
        $contents = $_POST['contents'];
        $this->model->addIO($name, $type, $concept, $contents);
        if (isset($_POST['otherIOs'])) {
            $otherIOs = $_POST['otherIOs'];
            $this->model->addOtherIOs($name, $otherIOs);
        }
        $NumArguments = func_num_args();
        if ($currentRelations!=null) {
            $IOs = $_POST['concetedIOs'];
            $this->model->setIoRelations($name,$IOs, $currentRelations);
        }
        exit;
        include_once 'Successful.php';
        $s = new Successful();
        $s->index("you add the io good");
}

但是当我打印数组 $currentRelations 时使用此语句:

echo count($currentRelations)

结果是1 not 2 ,当我使用语句 echo $currentRelations[0] 打印第一个元素时我得到e not eeeeee

这是为什么呢?解决办法是什么?我做错了什么?

最佳答案

正如我所评论的,$currentRalations 是一个字符串,因此在非数组或对象的任何类型上使用 count 将返回 1。
另请注意,当您对字符串执行此 $currentRelations[0] 操作时,您将访问该字符串从零开始的索引中的字符。由于字符串是字符数组,因此您可以使用方数组括号来访问字符串中的特定字符。这就是为什么 echo $currentRelations[0]; 在代码中打印 e 的原因。
要分割字符串,您应该使用 explode 函数,如下所示:

$curRel = explode(',', $currentRelations);

然后看看你会得到什么

var_dump($curRel);

希望有帮助。

关于php - 将数组作为一个变量从 JavaScript 发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10676645/

相关文章:

php - 在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集

php - 检查 MySQL 中是否存在值失败

jquery - 如何替换 HTML <select> 元素上的箭头按钮

jQuery 在下拉列表中选择的插件看起来很奇怪?

php - PHP mp3流在连接点出现问题

php - Zend Framework 的数据库组件的推荐实践?

Javascript:无法使用 for in 循环获取数组内的值

javascript - `dd-M-yyyy` 格式的日期解析字符串

javascript - 基本 Javascript 倒计时器的时间比设置的时间长

javascript - 将 .net 按钮控件 ID 传递给 JavaScript 函数