将命令curl转换为javascript

前端之家收集整理的这篇文章主要介绍了将命令curl转换为javascript前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将curl中的命令转换为 javascript.我在谷歌搜索,但我没有找到可以帮助我的解决方案或解释.命令curl是这样的:
  1. curl https://www.google.com/accounts/ClientLogin
  2. --data-urlencode Email=mail@example.com
  3. --data-urlencode Passwd=*******
  4. -d accountType=GOOGLE
  5. -d source=Google-cURL-Example
  6. -d service=lh2@H_404_3@
  7. 有了这个,我想将命令转换为$.ajax()函数.我的问题是,我不知道为了命令curl中存在的选项,我必须把函数setHeader放在哪里.

  8. $.ajax({
  9.             url: "https://www.google.com/accounts/ClientLogin",type: "GET",success: function(data) { alert('hello!' + data); },error: function(html) { alert(html); },beforeSend: setHeader
  10.     });
  11.     function setHeader(xhr) {
  12.        //
  13.     }@H_404_3@

解决方法

默认情况下,$.ajax()会将数据转换为查询字符串(如果不是字符串),因为这里的数据是一个对象,将数据更改为一个字符串,然后将processData:false设置为不会转换为查询字符串.
  1. $.ajax({
  2. url: "https://www.google.com/accounts/ClientLogin",beforeSend: function(xhr) {
  3. xhr.setRequestHeader("Authorization","Basic " + btoa("username:password"));
  4. },type: 'POST',dataType: 'json',contentType: 'application/json',processData: false,data: '{"foo":"bar"}',success: function (data) {
  5. alert(JSON.stringify(data));
  6. },error: function(){
  7. alert("Cannot get data");
  8. }
  9. });@H_404_3@

猜你在找的Linux相关文章