I am using jquery to build a request to the Twitter Search API. I am using jsonp, as is needed for cross-domain requests. However, the Twitter API specifies that you should set a unique User-Agent for these requests, and limits your requests if you do not. The problem is, I see no way of setting this header via jquery.
This is the code I am using:
$.ajax({
url: 'http://search.twitter.com/search.json',
dataType: 'jsonp',
type: 'get',
data: { q: 'twitter' },
success: function(data) {
alert(data.results);
}
});
I have tried using the beforeSend method, but it appears that this event is not firing. Can anyone come up with any way of solving this problem?
Thanks.
You can just set the Headers you want and just enter the URL in the browser, it will automatically take the headers from the extension when you hit the url. Only thing is, it will send headers for each and every URL you will hit so you have to disable or delete it after use. It works fine.
JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
Method to use JSONP: In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.
JSON with Padding works by adding a script element to the page, with the src attribute pointing to the URL of the web service. The web service then returns a script containing the data wrapped in a callback function that is executed when the script finishes parsing. It's not so much JSON (it doesn't even have to be valid JSON, for a start) as it is Plain JavaScript.
There's no way to modify the headers sent for a script element that's added to your page, unfortunately. The only thing you can do is check for a cross-origin compatible method of retrieving data, such as:
XMLHttpRequest Level 2 - Chrome, Safari 4+, Firefox 3.5+, Opera
// Is XMLHttpRequest Level 2 supported? if ("withCredentials" in new XMLHttpRequest())
XDomainRequest - for IE 8, IE 9
// Is XDomainRequest supported? if ("XDomainRequest" in window)
It would be a good idea to test for these implementations if they exist and use them accordingly, falling back to standard JSONP for unsupported or older browsers.
It's also possible (but unlikely, given that it's high profile) that the web service isn't set up to allow cross-origin requests, so you may still have to fall back to JSONP if the request fails. See also, Cross-Origin Resource Sharing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With