javascript - 尝试通过 AJAX 将 JS 数组传递给 PHP 脚本

标签 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来 self 的数组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结果当我通过$tags时出现错误到foreach环形。我知道数组在通过 POST 传递时应该采用键值对格式,但我不完全确定如何做到这一点,我想将其转换为 JSON在通过之前它可以解决问题,但它仍然不起作用。

非常感谢任何帮助。

最佳答案

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

在 php 中你可以使用 json_decode() :

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

这样,您就可以获得所需的数组。

关于javascript - 尝试通过 AJAX 将 JS 数组传递给 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248598/

相关文章:

javascript - 如何使显示内容具有响应性?

javascript - 如何检查 json 中的所有键是否都等于 true

php - 如何使用 php 从 mysql 数据库访问特定值?

php - 如何提取主题标签内容?

javascript - JQuery 工具提示位置

javascript - PHP - SQL - 单击按钮更新数据

javascript - Google Maps API JavaScript - 无显示,无错误

javascript - 为什么我在本地主机上的 Chrome 中收到 getCurrentPosition() 和 watchPosition() "insecure origins"错误?

javascript - 添加 Bootstrap 5 搜索栏下拉菜单

php - PHP 资源是立即释放还是应该使用 sqlsrv_free_stmt?