我尝试从URL获取Json对象。以下代码不起作用,他们没有给我一个错误或他们没有给我一些东西 我可以通过查看chrome中的url来获得Json结果。所以url名称中没有错误。 代码1:
<script type="text/javascript">
var url = "http://....; //I cant write url bcz of privacy reasons.
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://fantasy.premierleague.com/web/api/elements/100/').then(function (data) {
alert('Your Json result is: ' + data.result);
var o = JSON.parse(JSON.stringify(data));
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
// document.getElementById("avengers").innerHTML = o.provider[1].agentID+ " " + o.provider[1].nodeID;
// document.getElementById('avengers').innerHTML = o.result;
console.log(o);
}
//var names = o.proviver[0].agentID.toString();
//you can comment this, i used it to debug
}, function (status) { //error detection....
alert('Something went wrong.');
});
</script>
代码2:
$.ajax({
type: "GET",
url: '......',
dataType: 'json',
success: function(response){
console.table([response]);
// $('avengers').append(response.result)
}
});
还有其他办法吗?或者我完全错了。
答案 0 :(得分:-1)
$.post(url,
data={"key1":value1,"key2":value2,....}, //data={} if nothing to post
function(data,status)
{
if(status=="success")
{
console.log(data)
}
else
{
alert('fail')
}
}