jQuery.ajax() in node.js?


Question

Is it possible to use jQuery.ajax() in node.js exactly as it is syntax-wise?

I am trying to share non-UI browser code with node.js. I do not want to replace all the existing function calls with my own wrapper.

Currently when I try it, it would say "No Transport" by default because jQuery does domain detection. If I turn it off by setting jQuery.support.cors it would say XMLHttpRequest.open() not available.

1
32
12/26/2011 8:17:38 PM

Accepted Answer

I was able to solve the "No Transport" issue using the XMLHttpRequest module, like this:

var $ = require('jquery'),
    XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

$.support.cors = true;
$.ajaxSettings.xhr = function() {
    return new XMLHttpRequest();
};
40
6/13/2014 9:40:29 AM

also consider najax, a wrapper for the node request module which allows jquery style syntax for server-side requests

https://github.com/alanclarke/najax

var najax = require('najax');
najax('http://www.google.com', function(html){ console.log(html); });
najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST', success: function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){});

najax.get, najax.post, najax.put, najax.delete...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon