克,一天。有人可以帮助我弄清楚为什么我的代码没有将结果重新转换为json?我确信我的代码中有错误但似乎无法找到它。应该发生的是$ dept和$ box的值应该在警报中返回,但这不会发生。感谢
<?php
function runSQL($rsql) {
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "sample";
$connect = mysql_connect($hostname,$username,$password) or die ("Error: could not connect to database");
$db = mysql_select_db($dbname);
$result = mysql_query($rsql) or die ('test');
return $result;
mysql_close($connect);
}
$new = 1;
$items = rtrim($_POST['items'],",");
$sql = "SELECT * FROM `boxes` WHERE id IN ($items)";
$result = runSQL($sql);
$i = 0;
$rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
if ( $i < $rows ) {
$dept .= $row['department'] . "," ;
$box .= $row['custref'] . "," ;
} else {
$dept .= $row['department'];
$box .= $row['custref'];
}
$i++;
}
/*$items = rtrim($_POST['items'],",");
$sql = "UPDATE `boxes` SET status = 'Deleted' WHERE id IN ($items)";
$result = runSQL($sql);*/
//$sql = "INSERT INTO `act` (`item`) VALUES (\''.$box.'\')";
//$result = runSQL($sql);
$total = count(explode(",",$items));
$result = runSQL($sql);
$total = mysql_affected_rows();
/// Line 18/19 commented for demo purposes. The MySQL query is not executed in this case. When line 18 and 19 are uncommented, the MySQL query will be executed.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/x-json");
$json = "";
$json .= "{\n";
$json .= "dept: '".$dept.",'\n";
$json .= "box: '".$box."'\n";
$json .= "}\n";
echo $json;
?>
ajax
success: function(data){
dept = data.dept;
box = data.box;
alert("You have successfully deleted\n\r\n\rBox(es): "+data.dept+data.box);
$("#flex1").flexReload();
}
答案 0 :(得分:1)
$sql = "SELECT * FROM `boxes` WHERE id IN ($items)";
SQL注入漏洞。如果每个项目都是字符串,则必须mysql_real_escape_string
,或者确保它们只是数字,如果它们是它们应该是的(例如intval()
)。或者使用参数化查询。
header("Content-type: text/x-json");
application/json
。
$json .= "dept: '".$dept.",'\n";
除了需要在键和字符串值周围使用双引号的JSON之外,还需要将JavaScript-string-literal-escape值注入到字符串中。否则,撇号/ quote /反斜杠/换行符会破坏字符串。您最常使用addslashes()
执行此操作。
但实际上,没有人要求构建自己的JSON值(或其他JavaScript文字)。 PHP为您提供json_encode()
。它更简单,更快速,更可靠。使用它。
echo json_encode(array(
'dept'=>$dept,
'box'=>$box
));
答案 1 :(得分:0)
您的JSON不正确。它的格式如下:
{
dept: '...'
box: '...'
}
应该是:
{
"dept": "..."
"box": "..."
}
标识符需要在它们周围加上引号,字符串用引号括起来,而不是撇号。
答案 2 :(得分:0)
RFC4627将JSON的媒体类型定义为“application / json”。
答案 3 :(得分:0)
你写的
$json .= "dept: '".$dept.",'\n";
所以,
1.您应该为键和值添加双引号。
2.键值结束后没有逗号(,)。您将其添加到报价中。即你的代码将创建这个json,
dept: 'department,'
在那里看到逗号的地方。
试试这个:
$json .= "\"dept\": \"".$dept."\",\n";