D
D
dantedelvengo2019-02-18 17:45:51
PHP
dantedelvengo, 2019-02-18 17:45:51

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);


And this is how I try to send him a request and get a response:
1 option:

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);
            }
        });


But here it just gives an error textStatus as error

I try the 2nd option like this:

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();


Here, however, it simply does not produce anything,

however, in the first and second options, if you open the command line, you can see that the request passes and there is even an answer! 5c6ac4d4e6fe6088651743.png

Tell me what I'm doing wrong? and which option is better? I can’t call a request via php, since the application is written in JS and then it is assembled into apk via cordova

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dantedelvengo, 2019-02-19
@dantedelvengo

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);

if i call it like this:
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 );

then I get an answer and it shows what was written in id
, this option also works
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()

I'm glad that I finally got the simplest working version of api, now I can already start working on data validation, working with the database, etc. I hope this example will help someone else)

N
nvdfxx, 2019-02-18
@nvdfxx

fetch is better option than XMLHttpRequests

M
Michael, 2019-02-18
@nyakove

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 question

Ask a Question

731 491 924 answers to any question