我正在尝试创建基本身份验证页面,其中我的表单有三个字段
在提交表单时,我只想在JSON格式的HTML上显示来自服务器的返回响应.我对Web服务的AJAX调用还需要设置Authorization标头.但不知何故标题没有设置.我在尝试
beforeSend : function(xhr)
{
xhr.setRequestHeader('Authorization', "Basic ******");
xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
}
Run Code Online (Sandbox Code Playgroud)
但是当我在控制台中调试代码时,似乎断点永远不会进入这个功能.我是Ajax的新手,并通过在互联网上搜索下面的代码.我在下面发布完整的代码.
码:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = {
'username': $('#username').val(),
'password': $('#password').val(),
'grant_type': $('#grantType').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'http://localhost:9090/oauth/token',
beforeSend: function (xhr)
{
xhr.setRequestHeader("Authorization", "Basic ******");
xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
},
data : formData, // our data object
dataType : 'json', // what type of …Run Code Online (Sandbox Code Playgroud) 为解决CSRF问题,我使用Ajax的客户端设置:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the …Run Code Online (Sandbox Code Playgroud)