0

I'm loading cross domain html page with jQuery AJAX.

My problem is to return or equal the response data (target's html code) .

var html = "";

get("http://google.com");

function get( url ){

    $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
            var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
            options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
        }
    });

    $.get(url,function (response) {

         // Here is the problem

     });    
}

In the $.get() method I tried to :

html = result ;

return result ;

Both tries didn't work.

Is there any similar way to 'export' the response data to a global scope var ?

P.S - I've tried to use a function with a parameter to return the response . It worked perfectly but that is not what I want at all.

  • 3
    You can't do that. http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks May 06 '15 at 17:25
  • 1
    If you know where you want the data to go you can $(selector).html(response) it – Taplar May 06 '15 at 17:25
  • 1
    Appear to be asynchronous call , try performing tasks with `response` within callback `function(response)` . Can include `js` where `html` variable is expected to be utilized ? – guest271314 May 06 '15 at 17:27
  • 1
    for your particular requirement you have to make AJAX synchronous call. – vinayakj May 06 '15 at 17:35
  • Hum, thank you ! That's all I wanted to know, I'll research more about that, and try other ways to move further and improve it. Btw, feel free to mark it as duplicated, I'm closely sure it is . Have a nice day :D –  May 06 '15 at 17:35

1 Answers1

0

Try

// var html = "";

function get(url) {

  $.ajaxPrefilter(function(options) {
    if (options.crossDomain && jQuery.support.cors) {
      var http = (window.location.protocol === "http:" ? "http:" : "https:");
      options.url = http + "//cors-anywhere.herokuapp.com/" + options.url;
    }
  });

  return $.get(url);
};

get("http://google.com")
.then(function success(response) {
  // if request successful,
  // do stuff with `response` from requested `url`
  console.log(response)
}, function error(jqxhr, textStatus, errorThrown) {
  // if error , log `textStatus` , `errorThrown`
  console.log(textStatus, errorThrown)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

See .then()

guest271314
  • 1
  • 15
  • 104
  • 177