Reputation: 552
I have written a code for getting data from another server through JSONP call (based on jQuery) please look at the code below....
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
$.ajax({
type: "GET",
url: "http://www.dizainstore.com/chrome/info.php",
async: true,
data: "state="+ state+ "&city="+ city,
dataType: 'jsonp',
success: function(response) {
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
});
return false;
});
It's working fine for me. but When i used in Google Chrome Extension, it's not working, error occurred :- we can't use jquery Ajax call, they suggest xmlhttprequest. But i dont know how to convert this code into XMLhttpRequest. So please suggest me.
Thanks
Upvotes: 0
Views: 338
Reputation: 1289
If you want to make a cross-origin call in a Chrome extension, you don't have to use JSONP. You can simply use the Chrome extension cross-origin permissions: http://developer.chrome.com/extensions/xhr.html
Regards, Udi
Upvotes: 1
Reputation: 25830
Since the return is JSONP, it appears dizainstore is using a RESTful API and expects you to use JSONP with script injection:
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Your code would instead look something like this:
function handleDizain(response)
{
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
//Create a new script tag
var loader = document.createElement( "script" );
loader.setAttribute( "type", "text/javascript" );
//Set the source
loader.src = "http://www.dizainstore.com/chrome/info.php?state=" + state + "&city=" + city + "&callback=handleDizain";
//Add it to the body
document.body.appendChild( loader );
});
Upvotes: 1