How to call Apex REST API from Javascript?

Finally, I solved the problem. I'm pasting my code here for reference

    var result = sforce.connection.login("[email protected]", "mypassword+mysecurityToken");
    sforce.connection.init('{!sessionId}', 'REST web service url'); // here pass current session id of the org from which you are making request.

    sforce.connection.remoteFunction({
           url : REST web service url,
           requestHeaders: {"Authorization":"Bearer "+result.sessionId, "Content-Type":"application/json"}, // here pass the session id of the org in which you have your REST service
           requestData: data to post in JSON format,
           method: "POST",
           onSuccess : function(response) {
                  console.log(response);
              },
           onFailure : function(response) {
                  alert("Failed" + response)
              }
       });