15

I'm trying to convert a command in curl to javascript. I have searched in google but I don't find a solution or a explanation that can help me. The command curl is this:

curl https://www.google.com/accounts/ClientLogin 
--data-urlencode Email=mail@example.com 
--data-urlencode Passwd=******* 
-d accountType=GOOGLE 
-d source=Google-cURL-Example 
-d service=lh2

With this I want convert the command to $.ajax() function. My problem is that I don“t know what I have to put in function setHeader for the options present in command curl.

$.ajax({
            url: "https://www.google.com/accounts/ClientLogin",
            type: "GET",

        success: function(data) { alert('hello!' + data); },
        error: function(html) { alert(html); },
        beforeSend: setHeader
    });


    function setHeader(xhr) {
       //
    }
seal
  • 490
  • 2
  • 5
  • 20

1 Answers1

20

By default $.ajax() will convert data to a query string, if not already a string, since data here is an object, change the data to a string and then set processData: false, so that it is not converted to query string.

$.ajax({
 url: "https://www.google.com/accounts/ClientLogin",
 beforeSend: function(xhr) { 
  xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
 },
 type: 'POST',
 dataType: 'json',
 contentType: 'application/json',
 processData: false,
 data: '{"foo":"bar"}',
 success: function (data) {
  alert(JSON.stringify(data));
},
  error: function(){
   alert("Cannot get data");
 }
});
Ahmed_Ali
  • 1,672
  • 2
  • 24
  • 40