2

im trying to access database of twitter using json and jquery(only public tweets). I wrote a function. Here it is:

$(document).ready(function(){
alert("1");
$("button").click (function(){
    alert("2");
    $.getJSON("http://search.twitter.com/search.json?q=messi", function(data){
        alert("3");
    });
    alert("4");
});

} after page is loaded an alert appears and says 1, as expected. when i click the button two alerts appear and say 2, 4 respectively. It seems there is a problem with getJSON function i could not solve it.

otp
  • 77
  • 1
  • 5

1 Answers1

1

Your code infringes the Same Origin Policy by making a cross-domain request.

You can fix that by making it a JSONP request - which is not an Ajax request and not subject to the Same Origin Policy - by adding a callback=? parameter to the query string:

$.getJSON("http://search.twitter.com/search.json?q=messi&callback=?", function(data){
    alert("3");
});

Fiddle

jQuery.getJSON reference

When the request URL contains the callback=? parameter jQuery automatically assumes it as JSONP request and adds this abstraction layer which makes it "look like" an Ajax request. You can work with the data object which contains the parsed JSONP response.

ps. You may want to take a look at Dev Tools' (or Firebug's) console for development. It is non-blocking unlike alert and lets you display various data types and nested data structures.

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166