使用javascript发出json请求
我正在制作一个使用API的web应用程序。问题是,我从未使用javascript执行JSON请求(我曾经使用python)。这是我的密码:使用javascript发出json请求,javascript,json,api,python-requests,Javascript,Json,Api,Python Requests,我正在制作一个使用API的web应用程序。问题是,我从未使用javascript执行JSON请求(我曾经使用python)。这是我的密码: <head> <title>IP finder pro</title> <script> function find_ip() { var ip = document.getElementById('ip_input').value; fetch('http://ipap
<head>
<title>IP finder pro</title>
<script>
function find_ip() {
var ip = document.getElementById('ip_input').value;
fetch('http://ipapi.co/8.8.8.8/json')
.then(response => response.json())
.then(data => alert(data));
}
</script>
</head>
<body>
<input id="ip_input">
<button id="ip_button" onclick="find_ip()">Click !</button>
</body>
这是curl命令:
curl'https://ipapi.co/8.8.8.8/json/“
你知道我怎么做吗 您可以使用
fetch
API对JSON进行解码
您还可以使用Ajax
function ajax_get(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
try {
var data = JSON.parse(xmlhttp.responseText);
} catch(err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
ajax_get('your url', function(data) {
// Do stuff with it -> data["yourvalue"];
});
试试这个解决方案
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Obj = JSON.parse(this.responseText);
console.log(Obj);
}
};
xmlhttp.open("GET", "your_json_file.json", true);
xmlhttp.send();
我认为取回是最好的解决办法。但是,您需要注意的是,并非所有浏览器或其旧版本都支持它。例如,如果您需要支持蹩脚的IE,那么最好使用某种http请求库。它会返回以下信息:
[object object]
.mhh。。真奇怪。您能否提供该示例的实现?
function ajax_get(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
try {
var data = JSON.parse(xmlhttp.responseText);
} catch(err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
ajax_get('your url', function(data) {
// Do stuff with it -> data["yourvalue"];
});
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Obj = JSON.parse(this.responseText);
console.log(Obj);
}
};
xmlhttp.open("GET", "your_json_file.json", true);
xmlhttp.send();