Answer the question
In order to leave comments, you need to log in
Cross-domain request to Api on js - how to get data?
Good afternoon! There is such a php file not on the server for the test, just to display melon json
header("Content-type: application/json; charset: utf-8");;
$v['id'] ='11'; $v['nn']='22';
echo json_encode($v);
jQuery.ajax({
url: "http://www.***.com/hyst/acore.php",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
alert(resultData);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
var request = new XMLHttpRequest();
request.open('GET', 'http://www.***.com/hyst/acore.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
alert(data);
} else {
calert('error');
}
};
request.send();
Answer the question
In order to leave comments, you need to log in
Got it thank you all! the point was that in the handler file (acore.php) there was no permission
header('Access-Control-Allow-Origin: *');
now when the handler looks like this
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json; charset: utf-8");;
$v['id'] ='11'; $v['nn']='22';
echo json_encode($v);
fetch('http://www.****.com/hyst/acore.php')
.then(function(response) {
//alert(response.headers.get('Content-Type')); // application/json; charset=utf-8
//alert(response.status); // 200
return response.json();
})
.then(function(data) {
alert(data.id); // iliakan
})
.catch( alert );
var request = new XMLHttpRequest();
request.open('GET', 'http://www****.com/hyst/acore.php', false);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
alert(data.id);
} else {
alert('error');
}
};
request.send()
Most likely, the request does not have time to pass, because the payload does not get into the responseText. Solutions:
1) bad -
replace true with false so that the request is executed synchronously
2) good - use promises or async / await in the request
3) crutch - wrap response processing in setTimeout to let the code wait for the response, and then continue
setInterval(function() {
var data = JSON.parse(request.responseText);
alert(data);
}, 1000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question