更新:现在我可以看到数据已加载(从Chrome上的F12>网络)。但是跨度不会使用从JSON加载的数据进行更新:(
我犯了一个错误"Uncaught SyntaxError:Unexpected token",但经过数小时的搜索和测试,我不知道为什么。
index.html头:
<script type="text/javascript">
var displayResult = function(response){
$("#fruit_name").append(response.fruit_name);
$("#fruit_color").append(response.fruit_details.Color);
$("#fruit_taste").append(response.fruit_details.Taste);
}
var response = $.ajax({
type: "GET",
dataType:"json",
url: "https://www.domain.tld/api/?core=fruits&function=getFruits",
data: "",
success: displayResult
});
</script>
index.html正文:
<p>Fruit name : <span id="fruit_name"></span></p>
<p>Fruit color : <span id="fruit_color"></span></p>
<p>Fruit taste : <span id="fruit_taste"></span></p>
api文件(PHP):
$array = array(
"fruit_name" => "Tomato",
"fruit_details" => array(
"Color" => "red",
"Taste" => "acid"
)
);
echo json_encode($array,JSON_UNESCAPED_UNICODE);
api原始返回:
{"fruit_name":"Tomato","fruit_details":{"Color":"red","Taste":"acid"}}
有人能帮我吗?
内容JSON作为内容发送类型:application/JSON
谢谢。
url: "https://www.domain.tld/api/?core=fruits&function=getFruits&callback=?",
您在url中使用了一个callback
参数,这意味着jQuery将把它视为一个JSONP调用,而您的响应是无效的。删除它,您的响应将被正确解析为JSON:
url: "https://www.domain.tld/api/?core=fruits&function=getFruits",
这是jQuery代码:
$("#fruit_name" ).val(response.fruit_name);
$("#fruit_color" ).val(response.fruit_color);
$("#fruit_taste" ).val(response.fruit_taste);
确保附上:
$(document).ready(function() {
$("#fruit_name" ).val(response.fruit_name);
$("#fruit_color" ).val(response.fruit_color);
$("#fruit_taste" ).val(response.fruit_taste);
});