开发者

AJAX & Firefox?

开发者 https://www.devze.com 2022-12-16 08:19 出处:网络
I\'m trying to populate a div in html via ajax. The data source is a google search for \"bing sucks\" I call the method with

I'm trying to populate a div in html via ajax. The data source is a google search for "bing sucks"

I call the method with

loadXMLDoc('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Bing%20sucks')

It works in InternetExplorer, but it doesn't work with Firefox/Chrome. If I load just a file from the local domain (test.txt) , then it works.

What am I 开发者_Go百科doing wrong ?

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>AJAX</title>
<script language="javascript">



function loadXMLDoc(url)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET",url,false);
    xmlhttp.send(null);
    document.getElementById('test').innerHTML=xmlhttp.responseText;
}


</script>
</head>

<body>

    <div id="lol">
        lol
    </div>

<div id="test">
<h2>Click to let AJAX change this text</h2>
</div>


<button type="button" onclick="loadXMLDoc('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Bing%20sucks')">Click Me</button>
<button type="button" onclick="loadXMLDoc('test.txt')">Click Me</button></body>
</html>


You cannot use AJAX to read data from another domain.

You'll need to write a server-side script on your domain that sends a request to Google and forwards you the results.


Here comes the usual "just use jQuery" post!

Why not use jQuery? It'll get rid of all those browser inconsistencies for you:

<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript">
var url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Bing%20sucks';
$.getJSON(url + "&jsoncallback=?", function(data){
   $('#test').html(data);
});
</script>

You'd need some server-side programming to to intercept the request to get around the cross-domain issue. Normally you can't make an ajax request from one domain to the other.

See the jQuery docs on .getJSON. Previous question of similar nature.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号