我正在尝试通过 javascript array
到 php
使用 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/