我正在尝试使用 JQuery load()
将javascript array
传递给php
脚本。
这是我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() });
});
然后我从我的php script
访问POST
数组:
$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']));
这样,您就可以获得所需的数组。
你可以尝试json_decode来获取一个数组。
$tagsArray
已经是JSON格式。
只需提出这样的请求
$("#test").load("pages/ajax/save_tags.php", {
"tags": $tagArray ,
"name": $("#comp_name").val(),
"id": $("#comp_id").val(),
"type": $("#type").val()
});