将命令curl转换为javascript [英] Convert command curl to javascript

查看:124
本文介绍了将命令curl转换为javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将curl中的命令转换为javascript。我在谷歌搜索过,但我找不到可以帮助我的解决方案或解释。命令curl是:

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

有了这个我希望将命令转换为$ .ajax( )功能。我的问题是我不知道我必须在函数setHeader中输入命令curl中的选项。

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) {
       //
    }


推荐答案

默认情况下 $ .ajax()会将数据转换为查询字符串,如果还不是字符串,因为这里的数据是一个对象,将数据更改为字符串,然后设置 processData:false ,以便它不会转换为查询字符串。

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");
 }
});

这篇关于将命令curl转换为javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆