4 回答
TA贡献1890条经验 获得超9个赞
有几种解决方案,但在调用 json 链时不要在javascript/jquery中出错。
例如:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
TA贡献2039条经验 获得超7个赞
欢迎来到计算器!我们希望您喜欢这里。
正如@Anurag Srivastava 已经指出的那样,直接调用 url,你会得到 json,你不需要代理。
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TA贡献1812条经验 获得超5个赞
当你这样写的时候:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
你的 $info 是一个数组,cadena 也是一个数组。所以你可以像这样将 $cadenra 指向数组:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
或者像这样修复你的js:
alert(datos[0][0]);
TA贡献1779条经验 获得超6个赞
这是一种无需 Ajax 但使用的简单读取 JSON 的方法$.getJSON
在您的 PHP 文件中,因为您只想获得“cotizacion”数据更改:$cadena=array(0=>$info['cotizacion']如果$cadena=array(0=>$info['cotizacion'][0]您计划拥有并循环多个“cotizacion”,则可以删除 [0]
在你的 javascript 上使用:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
- 4 回答
- 0 关注
- 151 浏览
添加回答
举报