简体   繁体   English

将数组从jquery发送到PHP并返回

[英]Sending an array from jquery to PHP and back

I have a list of options (categories) of projects that the user can see. 我有用户可以看到的项目选项(类别)列表。 By selecting the categories, the div below should update with the lists of projects matching said categories. 通过选择类别,下面的div应该更新与所述类别匹配的项目列表。

Despite using the following answer, almost verbatim, Send array with Ajax to PHP script , I am still unable to retrieve any results, and yet no errors show up either. 尽管使用了以下答案,几乎是逐字记录, 将带有Ajax的数组发送到PHP脚本 ,但我仍然无法检索到任何结果,但是也没有出现错误。

The jquery: jQuery的:

// filter for projects
var $checkboxes = $("input:checkbox");

function getProjectFilterOptions(){
    var opts = [];

    $checkboxes.each(function(){
        if(this.checked){
            opts.push(this.name);
        }
    });

    return opts;
}

$checkboxes.on("change", function(){
    var opts = getProjectFilterOptions();

    //alert(opts);

    var categories = JSON.stringify(opts);

    $.ajax({
        url: "/web/plugins/projcat.php",
        type: "POST",
        dataType: "json",
        data: {data : categories},
        cache: false,

        success: function(data) {
            $('#projects').html(data);
            //alert(data);
        }
    });

});

the php (still in testing, so not filled out): php(仍在测试中,因此未填写):

<?php

if(isset($_POST['categories'])) {

    //echo "testing";
    $data = json_decode(stripslashes($_POST['categories']));
    print_r($data);
}
?>

Where is the error? 错误在哪里?

Try this: 尝试这个:

JS JS

...    
// dataType: "json",   // remove that; you're not sending  back JSON string
data: {categories : categories},
cache: false,
...

PHP PHP

<?php

if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {

    //echo "testing";
    $data = json_decode(stripslashes($_POST['categories']));

    // .. process the $data

    print_r($data);
    return;
}
?>

Your desired array is in $_POST['data'] and not in $_POST['projcats'] . 您所需的数组在$_POST['data'] ,而不在$_POST['projcats'] Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'] . data: {data : categories},更改为data: { projcats: categories },以使用$_POST['projcats']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM