Well after a few hickups I got it to work on my local machine as well as landfill and I thought I'd post the code and attempt to explain it.
First off you'll need to get a few YUI libraries, specifically the Connect Manager and the JSON library. For ease of my own use I just grabbed utilities.js, but that might be too much for some of you.
You'll need to set the Conent-Type properly:
YAHOO.util.Connect.setDefaultPostHeader( 'application/json', true );
You'll need to pick the Web Service you want to use by looking at the API here. Then you'll need to create the JSON to send over.
According to the JSON-RPC spec you send over an Object/Hash with 3 value pairs:
- method : the method you want to use, for this example we'll use Bug.add_comment
- params : the params the webservice docs say you need to send. The spec for JSON-RPC say it needs to be an array of objects, for Bug.add_comment is it just a hash of id and the comment and a few other optional things
- id : an integer, the id of the call so you can match it up later on, YUI should make it so we don't need to worry about this one, but you might care.
var myObject = {
"method": "Bug.add_comment",
"params": [
{
"id": 1,
"comment":"I am using bugzilla's webservices! YAY"
}],
"id": 1
};
and then we'll stringify it using YAHOO.lang.JSON.stringify.
var jsonObject = YAHOO.lang.JSON.stringify(myObject);
Now hopefully you know how to use the callback in YUI. If not there are plenty examples.
Finally you call it!
YAHOO.util.Connect.asyncRequest('POST', 'jsonrpc.cgi', callback, jsonObject );
So in this example I added a comment to bug 1, and that comment is
"I am using bugzilla's webservices! YAY"
That's it! The full code that I used is below. I was using firebug so you should change the console commands to whatever you want to do with the response:
YAHOO.util.Connect.setDefaultPostHeader( 'application/json', true );
var callback = {
success:function(o){
console.log('it worked');
console.dir(o.response);
},
failure:function(o){
console.log('it failed');
console.dir(o);
}};
var myObject = {
"method": "Bug.add_comment",
"params": [
{
"id": 1,
"comment":"I am using bugzilla's webservices! YAY"
}
],
"id": 1
};
var jsonObject = YAHOO.lang.JSON.stringify(myObject);
YAHOO.util.Connect.asyncRequest('POST', 'jsonrpc.cgi', callback, jsonObject );
Another example for those who would like one...
YAHOO.util.Connect.setDefaultPostHeader( 'application/json' );
var obj = {
"method": "Bug.get",
"params": [
{ "ids": [
1,
2
]
}
],
"id": 1
};
var jsonObj = YAHOO.lang.JSON.stringify(obj);
YAHOO.util.Connect.asyncRequest('POST', 'jsonrpc.cgi',
{ success:function(o){
console.log('it worked');
console.log(YAHOO.lang.JSON.parse(o.responseText));
},
failure:function(o){
console.log('it failed');
console.dir(o);
}
}, jsonObj);
No comments:
Post a Comment