试图通过AJAX将JS数组传递给PHP脚本

时间:2014-12-02 11:44:00

标签: javascript php jquery ajax

我正在尝试使用javascript arrayphp传递给JQuery load()脚本。

这是我的JQuery

$('#saveBtn').click(function(e){
    e.preventDefault();
    //Get hidden field values and store in an Array
    $tagArray = [];

    //Get the Checked Tags and store in an Array
    $('#tag_results :checked').each(function(){
          $tagArray.push(this.value);
    });

    //Make Ajax request to the add_tags script and pass Array as parameter. When response recieved show dialog. 
    //Pass the name, id and type of company with the array of tags to the save_tags.php script. 
    $('#test').load('pages/ajax/save_tags.php', {'tags': JSON.stringify($tagArray) ,'name': $('#comp_name').val(), 'id': $('#comp_id').val(), 'type': $('#type').val() });
});

然后,我从POST

访问php script数组
     $id = $_POST['id'];
     $name = $_POST['name'];
     $type = $_POST['type'];
     $tags = $_POST['tags']; //Should be an Array but is a String...

     //Type can be company, contact, column, supplement, programme. 
     if($type === 'company'){
         $company = new DirectoryCompany($id);
     }

     //Loop through the Tag array and add to the item. 
     foreach($tags as $tag){
         $company->addTag($tag, $id);    
     }

但是,当我执行var_dump($tags)时,我告诉它是String,而不是Array,因此当我通过{{1}时,我收到错误到$tags循环。我知道一个数组在通过POST传递时应该是一个键值对格式,但是我不能完全确定如何做到这一点,我想通过将它转换为foreach然后传递它就可以了但它仍然无法正常工作。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

您的变量$_POST['tags']也使用JSON编码,将其转换为字符串。

在php中你可以使用json_decode()

$tags = json_decode(stripslashes($_POST['tags']));

通过这种方式,您可以获得所需的数组。

答案 1 :(得分:2)

您可以尝试使用json_decode来获取数组。

答案 2 :(得分:0)

$tagsArray已采用JSON格式。

只需提出这样的请求

$("#test").load("pages/ajax/save_tags.php", {
    "tags": $tagArray ,
    "name": $("#comp_name").val(), 
    "id": $("#comp_id").val(), 
    "type": $("#type").val() 
});
相关问题