Javascript php ajax未返回预期结果,可能存在json解码问题
将以下代码粘贴到PHP中Javascript php ajax未返回预期结果,可能存在json解码问题,javascript,php,json,ajax,Javascript,Php,Json,Ajax,将以下代码粘贴到PHP中 $json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]'; $json2 = json_decode($json); foreach($json2 as $item){ $item->total = 9; } foreach($json2 as $item){
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 9;
}
foreach($json2 as $item){
print_r($item);
echo "<br>";
}
echo json_encode($json2);
现在,遵循同样的逻辑。将java脚本粘贴到下面
function test(){
var json = [{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}];
$.ajax({
url: base_url+"Product/ajax_test",
type: "POST",
dataType: "JSON",
data: {
'json':json,
},
success:function(data){
console.log(data);
}//end success function
});//end of ajax
}
并将php粘贴到下面,如果这有帮助,我将使用codeigniter框架
public function ajax_test(){
$json = $this->input->post('json');
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 2;
}
echo json_encode($json2);
}
我希望上面的2段代码在控制台中显示与我的“预期结果”类似的内容,但在控制台中没有显示任何内容。如果我把上面的代码改成下面的代码
public function ajax_test(){
$json = $this->input->post('json');
foreach($json as $item){
$item["total"] = 2;
}
echo json_encode($json);
}
上面的代码将在控制台中显示结果。“total”属性不在最终结果中,就好像它只是返回了原始的$json
变量一样。我需要使用$item[“total”]
而不是$item->total
,这也很奇怪
问题1,我在上述问题上做错了什么?
问题2,既然PHP是无状态的,我有没有办法排除ajax的问题,在控制台中回显PHP页面而不使用json编码?如果这样做有意义的话 json\u decode()
可以将json对象解码为对象或数组
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json_with_objects = json_decode($json);
$json_with_arrays = json_decode($json, true);
echo $json_with_objects[0]->quantity;
echo $json_with_arrays[0]["quantity"];
var_dump($json_with_objects);
var_dump($json_with_arrays);
大概,虽然我们无法知道,因为您没有提供它,但您的代码
$this->input->post()
正在使用关联数组而不是对象进行解码。我的回答有用吗?请看
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json_with_objects = json_decode($json);
$json_with_arrays = json_decode($json, true);
echo $json_with_objects[0]->quantity;
echo $json_with_arrays[0]["quantity"];
var_dump($json_with_objects);
var_dump($json_with_arrays);