How can I pass request headers with jQuery's getJSON() method?
I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'service.svc/Request',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
</script>
</head>
<body>
<h1>Some Text</h1>
</body>
</html>
If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:
- securityCode with a value of Foo
- passkey with a value of Bar
The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.
Hope this helps!
I think you could set the headers and still use getJSON() like this:
$.ajaxSetup({
headers : {
'Authorization' : 'Basic faskd52352rwfsdfs',
'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
}
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); });
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.