jQuery AJAX 自定义标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6351593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:43:39  来源:igfitidea点击:

jQuery AJAX Custom Header

jqueryajaxgoogle-chrome

提问by Denny

I'm trying to perform a request to the iContact API which required me to use a custom header for authentiation (http://developer.icontact.com/documentation/authenticate-requests). This is my code:

我正在尝试向 iContact API 执行请求,这要求我使用自定义标头进行身份验证 (http://developer.icontact.com/documentation/authenticate-requests)。这是我的代码:

$.ajax({
        type: "GET", 
        url: "https://app.icontact.com/icp/a/",
        contentType: "application/json",
        beforeSend: function(jqXHR, settings){
                jqXHR.setRequestHeader("Accept", "application/json");
                jqXHR.setRequestHeader("Api-Version", iContact_API_version);
                jqXHR.setRequestHeader("Api-AppId", iContact_appID);
                jqXHR.setRequestHeader("Api-Username", iContact_username);
                jqXHR.setRequestHeader("API-Password", iContact_appPassword);}
});

For some reason the request doesn't go through. However, when I perform the same request manually (using Chrome REST console) it works just fine. If I take out the custom headers (API-*), the request goes through but of course the authentication fails and I get back a regular HTML page.

由于某种原因,请求没有通过。但是,当我手动执行相同的请求(使用 Chrome REST 控制台)时,它工作得很好。如果我取出自定义标头 (API-*),请求会通过,但当然身份验证失败,我会返回一个常规的 HTML 页面。

I switched over to Firefox and checked Request/Response Headers:

我切换到 Firefox 并检查了请求/响应标头:

Request:

要求:

Host    app.icontact.com
User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Origin  http://184.72.61.244
Access-Control-Request-Me...    GET
Access-Control-Request-He...    api-appid,api-password,api-username,api-version

Response:

回复:

HTTP/1.1 302 Found
Date: Tue, 14 Jun 2011 23:43:56 GMT
Server: Apache/2.2.9 (Debian)
Set-Cookie: intellicontact_phpsess=1c7ca333017b47f46edd893dae584781; path=/; domain=.icontact.com; secure; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: https://app.icontact.com/icp/login/sentry.php?relurl=https%3A%2F%2Fapp.icontact.com%2Ficp%2Fa%2F&sess=
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 20
Connection: close
Content-Type: text/html; charset=utf-8

Any ideas what's going wrong here?

任何想法这里出了什么问题?

Thanks!

谢谢!

回答by DominikAngerer

The beforeSend hook is only available for $.ajaxSetup()so if you want to add it only to the $.ajax()you simply can go with the headersproperty.

beforeSend 钩子仅适用于$.ajaxSetup()因此如果您只想将其添加到$.ajax()您只需使用该headers属性即可。



If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

如果要将自定义标头(或标头集)添加到单个请求,则只需添加 headers 属性:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every requestthen use $.ajaxSetup():

如果要向每个请求添加默认标头(或标头集),请使用$.ajaxSetup()

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every requestthen use the beforeSendhook with $.ajaxSetup():

如果您想为每个请求添加一个标头(或一组标头),请使用beforeSend带有$.ajaxSetup()以下内容的钩子:

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info):One thing to be aware of is that with ajaxSetupyou can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetupmultiple times, only the last set of headers will be sent and only the last before-send callback will execute.

编辑(更多信息):要注意的一件事是,ajaxSetup您只能定义一组默认标头,并且只能定义一个beforeSend. 如果您ajaxSetup多次调用,则只会发送最后一组标头,并且只会执行最后一个发送前回调。

Source: https://stackoverflow.com/a/14655768/1581725

来源:https: //stackoverflow.com/a/14655768/1581725

回答by Ellipsis

It's strange that you are getting a 302 (Redirectional) in the response. Have you tried logging error with the Ajax function, to troubleshoot the problem? Here is an example of something I used.

奇怪的是,您在响应中收到了 302(重定向)。您是否尝试过使用 Ajax 功能记录错误以解决问题?这是我使用的一个例子。

console.log(" call back url :"+ callBackURL);
               $.ajax({
                    url: callBackURL,
                    type: 'post', //'GET' in your case    
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json' , // explicitly mentioning datatype
                    success: function(json) {
                        console.log(" reponse :"+ json);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log("error :"+XMLHttpRequest.responseText);
                    }


                }); 

回答by sheriff

please try this surely you can get the problem solve.

请试试这个,你肯定能解决问题。

  function FormSubmit()
  { 
  $.ajax({     
  type: "POST",
  url: 'index.php',
  data: $("#form_main").serialize(),
  async: false }).done(function( data ) {
  $("#Response").hide(); 
  if (isNaN(data)) {

  dispmsg = "<div class='alert alert-danger' role='alert'>Oops..Something had gone wrong! Please try again!</div>"; 
  $("#assess_me_response").html(dispmsg); setTimeout('ResetForm();',3000);
    } 
    else  { 

  dispmsg = "<div class='alert alert-success' role='alert'>Thank you for sharing the details. Our Consultant will contact you shortly!</div>"; $("#assess_me_response").html(dispmsg); setTimeout('Redirect();',3000); 

     }
       return true;
        });
  }