I'm trying to make a JavaScript Request to Json server configured on a site. I have handled the permissions on the site so I can save comments using a webservice module. The thing is that I must use JavaScript to do this and I have tried this:
function CommentThis()
{
var comment_object =
{
"nid": 3, "comment": "Hello!This is 开发者_开发知识库my comment...",
"cid": 2, "subject": "My comment", "uid": 1
};
var data=
{
"method": "comment.save",
"comment": comment_object
};
var jsonRequest = new Request.JSON(
{
url: "http://my_site.com/?q=services/json",
onSuccess: function(response){
var myDataArray = response['#data'];
document.writeln(myDataArray[16]);
}
}
).send({ data: data });
}
Firebug says that Request is not defined. The fact is that I don't know how to construct this Request JSON class. Please help.
If you are going to use that kind of functionality more often, I suggest using a Framework for that. I personally suggest jQuery, but since you are trying a Mootools function, you can try out that one. If you don't like either one of them, you can try out Prototype.
If you don't want to use any Framework, you have to use the XMLHTTPREQUEST object. W3C has a documentation on that.
You also don't want to use
document.writeln(myDataArray[16]);
Document.writeln() will blank out the entire page once the DOM has finished rendering. You want to manipulate the DOM using jQuery or mootools or the like. Also the response object probably needs to be parsed from Json to an object.
You can do this with the XMLHttpRequest
object. Here's a helper function to get you started.
function ajax( url, settings ) {
var ajax = new window.XMLHttpRequest(),
data = settings.type == 'GET' ? '' : settings.data;
url = settings.type == 'GET' ? url + ( settings.data ? '?' + settings.data : '' ) : url;
ajax.onreadystatechange = function () {
if ( ajax.readyState == 4 ) { //response ready
if ( ajax.status == 200 ) { //success
if ( settings.success ) settings.success( ajax.responseText, ajax.statusText );
} else {
if ( settings.error ) settings.error( ajax, ajax.status, ajax.statusText );
};
};
};
ajax.open( settings.type, url );
ajax.send( data );
};
And here's your function rewritten to use it:
function commentThis() {
var comment_object = {
"nid": 3, "comment": "Hello!This is my comment...",
"cid": 2, "subject": "My comment", "uid": 1
},
data = {
"method": "comment.save",
"comment": comment_object
};
ajax( "http://my_site.com/?q=services/json", {
"type": "GET",
"data": data,
"success": function ( data, status ) {
var myDataArray = data['#data'];
document.writeln(myDataArray[16]);
}
} );
};
精彩评论