基本身份验证使用jQuery / AJAX [英] Basic Authentication using jQuery/ajax

查看:247
本文介绍了基本身份验证使用jQuery / AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建基本身份验证的页面,我的表格有三个字段

I am trying to create basic authentication page where my form has three fields

  1. 用户名
  2. 密码
  3. 交付式

在提交表单我只是想显示从服务器上我的JSON格式的HTML返回的响应。 我的AJAX调用Web服务也需要授权头进行设置。 但不知何故,头都没有得到设置。我想

On submitting a form I just want to display returned response from a server on my HTML in JSON format. My AJAX call to web service also requires Authorization header to be set. But somehow headers are not getting set. I am trying

 beforeSend : function(xhr)
   {
       xhr.setRequestHeader('Authorization', "Basic ******");
       xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
    }

但是,当我在控制台调试code似乎断点从不进入该功能。 我是一个新手,Ajax和试图跌破code。通过谷歌搜索在互联网上。 我张贴低于整个code。

But when I debug the code in console it seems breakpoint never goes into this function. I am a newbie to Ajax and have tried below code by googling on the internet. I am posting whole code below.

code:

$(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 data do we expect back from the server
                        encode          : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 
                alert(data);

                // here we will handle errors and validation messages
            })

            .fail(function (jqXHR, textStatus){
                alert('Status : ' + textStatus + '' + JSON.stringify(jqXHR));
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

它所导致无法在我的code设置头。 请大家指正。

What it cause not to set headers in my code. Please correct me.

在控制台(谷歌浏览器)在网络选项卡上,我可以看到请求头下面

In console(Google Chrome) in Network tab, I can see below request headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type, contenttype
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.1.128:9090
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

和下面的错误出现在控制台中。

and below error appears in console.

和从高级REST客户端调用相同的API时扩展谷歌浏览器它为我所有的标题

And when calling same API from Advanced Rest Client extension for Google Chrome it shows me all the headers

User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
contentType: application/json;charset=UTF-8
Authorization: Basic **********
Content-Type: application/x-www-form-urlencoded 
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

我使用的文件协议只运行我的网页。

I am simply running my web page using file protocol.

例如:文件:/// E:/Mahendra/Practice%20Example/Test/OauthTest.html

我不知道这是否是引起一个问题。

I am not sure if this is causing a problem.

推荐答案

我通常添加页眉像这样(的code是一个查询使用SharePoint Web代理远程服务,的这里):

I usually add Headers like this ( the code is from a "Query a remote service using the web proxy in Sharepoint", here ) :

    $.ajax({
    url: "../_api/SP.WebProxy.invoke",
    type: "POST",
    data: JSON.stringify(
        {
            "requestInfo": {
                "__metadata": { "type": "SP.WebRequestInfo" },
                "Url": url,
                "Method": "GET",
                "Headers": {
                    "results": [{
                        "__metadata": { "type": "SP.KeyValue" },
                        "Key": "Accept",
                        "Value": "application/json;odata=verbose",
                        "ValueType": "Edm.String"
                    }]
                }
            }
        }),
    headers: {
        "Accept": "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "Authorization": "yourkeyvalueforauthorizationEXAMPLE",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: successHandler,
    error: errorHandler
});

让我知道如何去

这篇关于基本身份验证使用jQuery / AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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