将 JavaScript 变量传递给 PHP 函数并正确引用它
passing a javascript variable to a php function and quoting it correctly
Im using Zend Framework ..在我的一个 phtml 文件中,我有这段代码
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
如何正确地将js元素传递给php函数
php函数(已经想到通过ajax来做。它相当复杂)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
如果使用 jQuery,则可以执行以下操作来执行 JSON 请求:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
您可以将现有的 PHP 代码与此解决方案一起使用。 您指向的 url 只需要打印 JSON 结果,就像您目前在 getparentids()
中所做的那样。
相关文章:
- 这在 Object 方法中不引用对象,而是引用函数绑定到的标记
- Javascript在引用函数到变量时等于这个
- 引用函数数组中的另一个函数
- window.load上单独的javascript文件中的引用函数
- 如何引用函数
- JavaScript:函数字典:函数可以从其字典中引用函数
- 未捕获的引用函数上的错误
- 从不同的.JS文件中引用函数中的数组
- 动态引用函数时的Javascript变量范围
- 函数作为对象中的属性:引用函数内部的其他属性
- 在Javascript中,如何引用函数范围内的变量,该变量来自在该函数中调用但在其他地方定义的函数
- 在IIFE中引用函数
- 如何从函数自己的实现中引用函数
- 是否可以从HTML文件中的特定脚本标签引用函数或对象?
- 在函数中引用函数的属性
- 在'class'在同一个类中引用函数不起作用
- 从JavaScript对象内的函数中引用函数
- JavaScript函数被事件监听器多次调用,即使我引用函数
- 在angularjs中的$scope成员函数中引用函数中的变量
- 如何用文档引用函数