Neither:
var response = $.ajax({
type: \"GET\",
url: \"http://www.google.de\",
async: false,
success : function() {
alert (this
You simply must rewrite it like that:
var response = '';
$.ajax({ type: "GET",
url: "http://www.google.de",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).
And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)
This is super old, but hopefully this helps somebody. I'm sending responses with different error codes back and this is the only solution I've found that works in
$.ajax({
data: {
"data": "mydata"
},
type: "POST",
url: "myurl"
}).done(function(data){
alert(data);
}).fail(function(data){
alert(data.responseText)
});
Since JQuery deprecated the success
and error
functions, it's you need to use done
and fail
, and access the data with data.responseText
when in fail
, and just with data
when in done
. This is similar to @Marco Pavan 's answer, but you don't need any JQuery plugins or anything to use it.
As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.
For example, if you were using PHP, you could:
Create the file web_root/ajax_responders/google.php with:
<?php
echo file_get_contents('http://www.google.de');
?>
And then alter your code to connect to that instead of to Google's domain directly in the javascript:
var response = $.ajax({ type: "GET",
url: "/ajax_responders/google.php",
async: false
}).responseText;
alert(response);
Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.
Suppose a PHP file responder.php has these contents:
$url = "https://www.google.com";
$ch = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;
Your AJAX request should be to this responder.php file so that it executes the cross-domain request.
Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3
Webkit and IE8 supports it as well in some fashion.