将命令 curl 转换为 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26274544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert command curl to javascript
提问by seal
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 中的命令转换为 javascript。我在谷歌搜索过,但没有找到可以帮助我的解决方案或解释。命令 curl 是这样的:
curl https://www.google.com/accounts/ClientLogin
--data-urlencode [email protected]
--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() 函数。我的问题是我不知道我必须在函数 setHeader 中为命令 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) {
//
}
回答by Ahmed_Ali
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()会将数据转换为查询字符串,如果还不是字符串,由于这里的数据是一个对象,将数据更改为字符串然后设置processData: false,这样就不会转换为查询字符串。
$.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");
}
});

