Javascript 如何在ajax响应中使用php获取编码json的值?
您好,我正在使用上面的PHP代码获得一个JSON数据,如下所示Javascript 如何在ajax响应中使用php获取编码json的值?,javascript,php,ajax,Javascript,Php,Ajax,您好,我正在使用上面的PHP代码获得一个JSON数据,如下所示 echo json_encode(array('out' => $out, 'total' => $total )); 我需要在一个单独的变量中获取元素,如下所示 var result = {"out":"[{\"tax\":\"SGST@9%\",\"percent\":7.75},{\"tax\":\"CGST@9%\",\"percent\":7.75},{\"tax\":\"SGST@2.5%\",\"perc
echo json_encode(array('out' => $out, 'total' => $total ));
我需要在一个单独的变量中获取元素,如下所示
var result = {"out":"[{\"tax\":\"SGST@9%\",\"percent\":7.75},{\"tax\":\"CGST@9%\",\"percent\":7.75},{\"tax\":\"SGST@2.5%\",\"percent\":3.11},{\"tax\":\"CGST@2.5%\",\"percent\":3.11}]","total":210}
到目前为止,我尝试了以下代码
var out = [{"tax":"SGST@9%","percent":7.75},{"tax":"CGST@9%","percent":7.75},{"tax":"SGST@2.5%","percent":3.11},{"tax":"CGST@2.5%","percent":3.11}];
var total = 210;
但是我没有得到任何输出。基本问题是,
$out
一开始是JSON(因此它最终被双重编码),但在上下文中是JSON没有意义
在将更广泛的数组转换为JSON之前,您可以将其转换为PHP数据结构:
result = JSON.stringify(result);
result = result.replace(/\\/g, "");
var obj3 = JSON.parse(result);
alert(obj3[0]);
如果您不想接触PHP,可以使用JavaScript解决这一问题:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
在Ajax设置中,添加
JSON
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
?>
var out_json = result.out;
var out = JSON.parse(out_json);
然后在你的成功功能中
dataType: 'JSON',
您不需要在js中执行任何操作。只需像
result.tax
一样访问它即可。只要您的Ajax设置为接收JSON
非常感谢,这就行了
success: function(result) {
console.log(result.tax);//gives you the value for the tax key provided it's defined in the php response array
},