如何将此curl脚本转换为JavaScript中的AJAX请求?
curl -X POST
-d "grant_type=password&username=admin&password=Demo1234"
-u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth
答案 0 :(得分:2)
您的curl
来电使用了三件事:
这是我最好的想法:
$.ajax({
"url": "http://<host>/url/to/auth",
"data": "grant_type=password&username=admin&password=Demo1234",
"processData": false,
"beforeSend": function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
}
});
将您的<ClientID>
和<ClientSecret>
替换为正确的值。
答案 1 :(得分:2)
我将在纯JavaScript
function sendData()
{
var formData = new FormData(); //create formData object to send data
formData.append("grant_type, "password"); //via append you add data
formData.append("username", "admin");
formData.append("password", "Demo1234");
var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
xmlHttp.onreadystatechange = function() //monitor status of response
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
{
console.log(xmlHttp.responseText); //then output data
}
}
xmlHttp.open("POST", "http://<host>/url/to/auth");
xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
xmlHttp.send(formData);
}
答案 2 :(得分:1)
以下是任何卷曲的方法,而不仅仅是这个:
其中一个代码段导出器是jqueryAjax。