我正在尝试通过API登录,这在Postman和Android应用程序中运行良好,但它在我的网页中出错。
我在Android应用和邮递员中可以接受我在数据中输入的用户名。
$(document).ready(function() {
var mUrl = "http://18.218.238.174/kuru-service/oauth/token";
$("#loginBtn").click(function() {
$.ajax({
type: 'POST',
url: mUrl,
data: {
"grant_type": "password",
"username": "mak",
"password": "1234"
},
dataType: "jsonp",
headers: {
"Authorization": "Basic a3VydS1pb3MtYXgitBwOmt1cnUtc2VydmljZQ==",
"Content-Type": "application/x-www-form-urlencoded"
},
success: function(data) {
console.log(data);
alert("success");
},
error: function(data, errorThrown) {
console.log(data);
console.log(errorThrown);
}
});
});
});
答案 0 :(得分:0)
您无法通过浏览器拨打跨域电话。你可以发一个jsonp请求。以下是您可以使用的示例代码。
call_ajax = function(options){
var data_str = '', url_str = '';
if (!options) {
alert('Please pass ajax parameters');
return false;
}
if (!options.url){
alert('Please pass server url to call');
return false;
}
/* Assign onload/success and onerror/error functions */
onload_fn = (typeof options.success == 'function') ? options.success : function(){};
onerror_fn = (typeof options.error == 'function') ? options.error : function(){};
/* convert data dict to url parameters string */
if (options.data){
if ( typeof options.data == 'object'){
for (key in options.data){
if (options.data[key]){
data_str = data_str + '&' + key + '=' + encodeURIComponent(options.data[key]);
}
}
} else if (typeof options.data == 'string'){
data_str = '&' + options.data;
}
}
/* get final url having url parameters string */
url_str = (options.url.indexOf('?') > 0) ? options.url + data_str : options.url + '?' + data_str.slice(1);
/* add script tag with all values */
loadScript(url_str, onload_fn, onerror_fn);
};
loadScript = function(src, onload, onerror) {
var head = document.getElementsByTagName('head')[0] || document.documentElement;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
if (script.readyState){
script.onreadystatechange = function () {
var state = this.readyState;
if (state === 'loaded' || state === 'complete') {
script.onreadystatechange = null;
onload();
}
};
}
else{
script.onload = onload;
}
script.onerror = onerror;
head.appendChild(script);
};
call_ajax({
url: "http://18.218.238.174/kuru-service/oauth/token",
data: {
"grant_type": "password",
"username": "mak",
"password": "1234"
},
success: success_fn,
error: error_fn
});