I am somewhat novice at javas开发者_如何学JAVAcript, but I am trying to call a JSON web service that require basic authentication using jQuery (or anything that would work really).
I've not been able to come up with any real answers on Google. Is what I am trying to do possible?
You will need to set the appropriate request header to pass the credentials. For example see here.
$.getJSON({
'url': 'http://host.com/action/',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
//May need to use "Authorization" instead
xhr.setRequestHeader("Authentication",
"Basic " + encodeBase64(username + ":" + password)
},
success: function(result) {
alert('done');
}
});
FYI I searched Google for jquery post with basic auth
and this was the first link.
Here's the way to do it with jQuery for your copy and pasting needs:
$.ajax({
url: "/somewhere",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
},
success: function(result) {
console.log(arguments);
}
});
Simple.
In asp.net create a reference to the service. Create a web page (with no UI) and make multiple methods in the code behind that are "wrappers" for that service (in C#/VB.NET). Decorate the methods with [WebMethod] and set the WebMethod's Serialization to JSON.
Alternatively you can do the same with any other language (pearl, php, whatever) by making a wrapper for the json web service.
The reason you need that wrapper is because that way you avoid the cross-site scripting... limitations in JS. Also if your page is served over HTTPS, than your JS calls to your wrapper will also be over HTTPS thus not having to worry about security.
Your JS wrapper will be taking care of negotiating the connection, authentication, etc...
The javascript within your other pages can post to the methods in this page as:
$.post('pagename/method_name', {data:value}, callback(){
});
or $.post, $.get, $.ajax... will all work.
精彩评论