如何自定义HTTP报头,以用于所有Ajax请求?

我正在做一个项目,遇到了一个到目前为止我一直无法解决的问题。

该项目是一个使用jQuery移动框架构建的移动Web应用程序,Web应用程序可以从WCF服务中提取json并使用jQuery移动UI效果呈现它。我们已经到了实现基于令牌的安全的阶段,这就是我的问题所在。在这里,我想添加一个自定义HTTP报头,用于所有其他Ajax请求。

function login_service()
{
    //$.mobile.pageLoading();
    var stringUsername = $('#txtUsername').val();
    var stringPassword = $('#txtPassword').val();
    $('#loginMessage').empty(); // Empty message div        
$.ajax(
    {
        url: "urlstring"+stringUsername+"/"+stringPassword, // This URL uses https
        dataType: "jsonp",
        type: 'GET',
        beforeSend: setHeader,
        success: function(loginResult)
        {
            $('#loginMessage').html('<a>'+ loginResult.tkt + '</a>');
            tkn = loginResult.tkt; // Json token
            if(tkn == null)
            {
            $('#loginMessage').append("invalid login:" + '&nbsp;' + '<br>' + "token:" + '&nbsp;' + tkn);
            $.mobile.pageLoading(true);
            }
            else
            {
                $.mobile.changePage('#search'); // Change page to search screen
            }

        },
        error: function(status)
        {
            alert(status);
            $.mobile.pageLoading(true); // End loading animation
        }
    })
}

function setHeader(xhr) 
{                
    xhr.setRequestHeader('Authorization', tkn); 
    alert("header set");              
} 

function doSearch_webservice(){ // Start of function webservice
$.ajax({ // Start of ajax call
url: "urlstring"+$('#jsonSearch').val(), // If URL string is http, custom header will
         // be displayed in fiddler/firebug. IF HTTPS custom header won't work.
dataType: 'jsonp',
type: 'GET',
timeout: '20000',
beforeSend: setHeader,
success: function(json_results)
    {// Start of success function 
        if(json_results.keys == null)
            {
                $('#errMessage').html('<p class="error"><strong>'+ "Status:" 
                + "No record found" + "<br>Please try again" +'</strong> </p>');    
                $.mobile.pageLoading(true);
            }
        else
            {

                $('#jsonResponse ul').remove();
                // jquery mobile type i.e. data-inset
                $('#jsonResponse').append('<ul class="listItems" data-role="listview"  data-inset="true"></ul>');
                var listItems = $('#jsonResponse').find('ul');
                $.each(json_results.keys, function(key) { // Start of each loop

                html= 
                '<a href="#" data-transition="slide" data-position="inline"OnClick="passQryStrg(\''+json_results.keys[key].id+'\' ,  \''+json_results.keys[key].cat+'\' );">'+'<br>'+' '+'<font class="big-text"><b>'+' '+json_results.keys[key].lbl[0]+' '+'</font></b>'+' '+'<font class="small-text">'+' '+'<br>'+' '+json_results.keys[key].lbl[1]+' '+'</font>'+'</a>'

                listItems.append('<li>'+html+'</li>');
                }); // End of each loop
            $('#info jsonResponse ul').listview();
            $.mobile.pageLoading(true); 
            $.mobile.changePage( "#info", { transition: "slide"} );
            $("#info").page("destroy").page(); 
            }
                 // Destroy the page - next function call won't break css
        }, // End of success function   
        error: function(jqXHR, textStatus, errorThrown)
            {
                $('#errMessage').html('<p class="error"><strong>'+ "Status:" + textStatus + "<br>Please try again" +'</strong> </p>');  
                $.mobile.pageLoading(true);
                }
            }); // End of ajax call 
}; // Emd of webservice function

如果do_search ajax请求使用http网址,则会添加自定义标头。但是我需要将URL更改为我们的wcf服务使用的https,当我进行此更改时,自定义标头则会停止工作。抱歉,如果我的解释不清楚,我会尽力回答您的问题。

多谢帮助!

You should use the headers options of jQuery.ajax().

A map of additional header key/value pairs to send along with the request

So you'll need to pass your headers this way:

$('...').ajax(function() {
  url: ... ,
  data: ... ,
  headers: {
    'Authorization': tkn
  }
});

If you JSON token is a string, just convert it before with jQuery.parseJSON() :

var tkn = $.parseJSON(tokenString);

I have solved the problem I have been having.

When using an xmlHttpRequest object to create a custom HTTP request header. Or in my case since I have been using jquery, an ajax request. Both the webpage making the request and the request itself must use a url with the same protocol. E.g. https. If the webpage has a http url and its making a ajax request with https, this will not work.

This is because of the Same Origin Policy as defined on http://www.w3.org/Security/wiki/Same_Origin_Policy won't allow it. It is to protect websites from security vulnerabilities. Without such security, scripts can exploit website vulnerabilities.

Hopefully this will help anybody who gets stuck on this particular problem.