Ody*_*3us 2 php ajax jquery json
我正在尝试使用PHP解析JSON字符串,使用$.ajax
此格式的jQuery将JSON发送到PHP文件[{"value":"59"},{"value":"7"},{"value":"46"}]
,但由于一些奇怪的原因我不断收到此错误"Invalid argument supplied for foreach()"
,这是我的PHP和jQuery代码,
jQuery的:
$(".systems").each( function(i, system) {
// for each location block
system = $(system);
var sys = {
'value' : $("select[data-prod='products']", system).val()
};
allSystems.push( sys );
});
$.ajax({
type: 'POST',
url: 'systems.php',
dataType: 'json',
data: { systems: JSON.stringify(allSystems), uid: uid },
success: function(data){
alert(data)
}
});
Run Code Online (Sandbox Code Playgroud)
PHP:
require_once 'classes/Zend/Json.php';
$json = $_POST['systems'];
$uid = $_POST['uid'];
$array= Zend_Json::decode("$json");
mysql_connect('localhost','user','pass') or die(mysql_error());
mysql_select_db('products') or die(mysql_error());
//insert the suppliers products into the database
foreach($array as $key){
$query = mysql_query("INSERT INTO suppliersProducts (product_id, supplier_id) VALUES('".$key['value']."', '".$uid."' ) ") or die(mysql_error());
}
print_r($json);
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在使用Zend框架的JSON解码函数来解码传递给PHP的JSON字符串,并且该格式对我来说似乎是正确的,所以我不知道它可能导致此错误,也许编码?有任何想法吗?
Thanx提前!
看起来json_decode()无法处理该post参数中的数据.在脚本中添加一些错误处理.
$test = json_decode($json, true);
if ( is_null($test) ) {
die('data is not encoded as valid json');
}
else if ( !is_array($test) ) {
die('Unexpected data structure. Array expected.');
}
Run Code Online (Sandbox Code Playgroud)
您可能也对json_last_error()感兴趣
更新:也许这是一个编码问题.由于您无权访问json_last_error(),因此您可能需要"手动"检查字符串和编码,例如
if ( is_null($test) ) {
// <--- for debugging purposes only
echo '<pre>Debug: $json=';
var_dump($json);
echo 'hex=';
for($i=0; $i<strlen($json); $i++) {
printf('%02X ', ord($json[$i]));
}
echo '</pre>';
// for debugging purposes only -->
die('data is not encoded as valid json');
Run Code Online (Sandbox Code Playgroud)
在将值作为字符串文字混合到sql语句中时,还必须使用mysql_real_escape_string(),请参阅CWE-89:SQL命令中使用的特殊元素的不正确中和('SQL注入')
$mysql = mysql_connect('localhost','user','password') or die(mysql_error());
mysql_select_db('products', $mysql) or die(mysql_error($mysql));
...
$sql = "
INSERT INTO
suppliersProducts
(product_id, supplier_id)
VALUES
(
'" . mysql_real_escape_string($key['value'], $mysql) . "'
, '" . mysql_real_escape_string($uid, $mysql) . "'
)
";
$query = mysql_query($sql, $mysql) or die(mysql_error($mysql));
Run Code Online (Sandbox Code Playgroud)
甚至更好:使用准备好的参数化查询,参见例如PDO - 准备好的语句和存储过程
归档时间: |
|
查看次数: |
1945 次 |
最近记录: |