programing

패스는 jquery ajax에 헤더 매개 변수를 허용합니다.

copysource 2021. 1. 17. 11:50
반응형

패스는 jquery ajax에 헤더 매개 변수를 허용합니다.


Chrome 콘솔에서 다음 코드를 검사하면 요청 헤더가 표시됩니다. Accept:undefined

jQuery.ajax({
        url: _this.attr('href'),
        accepts: "application/json; charset=utf-8",

    });
});

수락 유형을 json으로 설정하는 방법은 무엇입니까? 사용자 지정 헤더를 설정하거나 사용하고 싶지 않습니다.beforeSend


이 시도 ,

$.ajax({     
  headers: {          
    Accept: "text/plain; charset=utf-8",         
    "Content-Type": "text/plain; charset=utf-8"   
  }     
  data: "data",    
  success : function(response) {  
    // ...
  }
});

이 게시물을 참조하십시오.

jQuery로 Accept HTTP 헤더를 올바르게 설정할 수 없습니다.


수락 헤더를 설정하는 두 가지 대체 방법은 다음과 같습니다.

1) setRequestHeader('Accept','application/json; charset=utf-8');

2) $.ajax({
    dataType: ($.browser.msie) ? "text" : "json",
    accepts: {
        text: "application/json"
    }
});

최신 버전의 jQuery에서 "dataType"을 적절한 값으로 설정하면 accepts 헤더도 설정됩니다. 예를 들어, dataType: "json"수락 헤더를로 설정합니다 Accept: application/json, text/javascript, */*; q=0.01.


다른 답변은 실제 질문에 대한 답변이 아니라 accepts매개 변수 의 올바른 구문을 파악하는 데 문자 그대로 10 초가 걸리기 때문에 부끄러운 해결 방법을 제공합니다 .

accepts매개 변수는 매핑 오브젝트 소요 dataType받는 Accept헤더를. 귀하의 경우 accepts에는 데이터 유형을 설정하는 json것으로 충분해야하므로 객체 를 전달할 필요조차 없습니다 . 그러나 사용자 정의 Accept헤더 를 구성 하려면 다음을 수행하십시오.

accepts: {"*": "my custom mime type" },

내가 어떻게 알아? jquery의 소스 코드를 열고 "accepts"를 검색합니다. 첫 번째 발견은 알아야 할 모든 것을 알려줍니다.

    accepts: {
        "*": allTypes,
        text: "text/plain",
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript"
    },

당신이 보는 것처럼은 기본적 매핑이 text, html, xmljson데이터 유형.


이 시도:

$.ajax({
        beforeSend: function (xhr){ 
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.setRequestHeader("Accept","text/json");
    }, 
    type: "POST",
    //........
});

그들 중 일부는 정확하지만 이전 답변이 상당히 혼란 스럽습니다. 동시에 OP는 사용자 정의 헤더를 설정하거나 사용하지 않고 솔루션을 요청 beforeSend했기 때문에 더 명확한 설명을 찾고 있습니다. 내 결론이 다른 사람들에게 빛이되기를 바랍니다.

코드

jQuery.ajax({
    .... 
    accepts: "application/json; charset=utf-8",
    ....
});

때문에 작동하지 않습니다 accepts해야합니다 PlainObject(안 StringJQuery와 문서에 따라) ( http://api.jquery.com/jquery.ajax/ )를. 특히 jQuery dataType는 허용 된 MIME 유형 과 각각 관련되는 0 개 이상의 키-값 쌍을 예상 합니다. 그래서 내가 마지막으로 사용한 것은 다음과 같습니다.

jQuery.ajax({
    ....
    dataType: 'json',
    accepts: {
        json: 'application/json'
    },
    ....
});

You had already identified the accepts parameter as the one you wanted and keyur is right in showing you the correct way to set it, but if you set DataType to "json" then it will automatically set the default value of accepts to the value you want as per the jQuery reference. So all you need is:

jQuery.ajax({
    url: _this.attr('href'),
    dataType: "json"
});

I use jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] ) for example:

var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Failed to obtain JSON data from server: " + err );
  }); /* failed to get JSON */

getJSON is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

ReferenceURL : https://stackoverflow.com/questions/12347211/pass-accepts-header-parameter-to-jquery-ajax

반응형