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條經驗 獲得超8個贊
歡迎來到計算器!我們希望您喜歡這里。
正如@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 關注
- 181 瀏覽
添加回答
舉報