IT story

$ .ajax-dataType

hot-time 2020. 7. 9. 07:58
반응형

$ .ajax-dataType


차이점은 무엇입니까

contentType: "application/json; charset=utf-8",
dataType: "json",

vs.

contentType: "application/json",
dataType: "text",

  • contentType 특정 형식을 지정하여 서버로 전송되는 헤더입니다.
    • 예 : json 또는 XML을 보내고 있습니다.
  • dataType jQuery에게 어떤 종류의 응답을 기대하고 있는지 말하고 있습니까?
    • JSON, XML 또는 HTML 등을 기대합니다 ... jQuery가 기본적으로 시도하고 알아내는 것이 기본입니다.

$.ajax()문서 뿐만 아니라 이러한 대한 자세한 설명이 있습니다.

특정 경우 첫 번째는에 응답을 요청 utf-8하고 두 번째는 상관하지 않습니다. 또한 첫 번째는 응답을 자바 스크립트 객체로 처리하고 두 번째는 응답을 문자열로 처리합니다.

첫 번째는 다음과 같습니다.

success: function(data) {
  //get data, e.g. data.title;
}

두번째:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

(ps : Nick Craver의 답변이 잘못되었습니다)

contentType은 요청의 일부로 서버에 전송되는 데이터의 형식을 지정합니다 (응답의 일부로도 나중에 전송할 수 있음).

dataType은 클라이언트 (브라우저)가받을 데이터의 예상 형식을 지정합니다.

둘 다 교환 할 수 없습니다.

  • contentType서버로 전송되는 데이터 형식 (즉, 메시지 본문의 내용)을 지정하여 서버로 전송되는 헤더입니다. 이것은 POST 및 PUT 요청과 함께 사용됩니다. 일반적으로 POST 요청을 보낼 때 메시지 본문은 다음과 같은 매개 변수로 전달됩니다.

================================

샘플 요청 :

POST /search HTTP/1.1 
Content-Type: application/x-www-form-urlencoded 
<<other header>>

name=sam&age=35

================================

"name = sam & age = 35"위의 마지막 행은 메시지 본문이며 contentType은 메시지 본문에 양식 매개 변수를 전달하기 때문에 application / x-www-form-urlencoded로 지정합니다. 그러나 매개 변수를 보내는 것에 만 국한되지 않고 json, xml 등을 보낼 수 있습니다 (다른 유형의 데이터를 보내는 것이 RESTful 웹 서비스에 특히 유용합니다).

================================

샘플 요청 :

POST /orders HTTP/1.1
Content-Type: application/xml
<<other header>>

<order>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

================================

이번에는 ContentType이 application / xml입니다. 이것이 우리가 보내는 이유입니다. 위의 예제는 샘플 요청을 보여주었습니다. 마찬가지로 서버에서 보낸 응답은 서버가 다음과 같이 보내는 것을 지정하는 Content-Type 헤더를 가질 수 있습니다.

================================

샘플 응답 :

HTTP/1.1 201 Created
Content-Type: application/xml
<<other headers>>

<order id="233">
   <link rel="self" href="http://example.com/orders/133"/>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

================================

  • dataType예상되는 응답 형식을 지정합니다. Accept 헤더와 관련이 있습니다. JQuery는 응답의 내용 유형을 기반으로 추론하려고 시도합니다.

================================

샘플 요청 :

GET /someFolder/index.html HTTP/1.1
Host: mysite.org
Accept: application/xml
<<other headers>>

================================

위의 요청은 서버에서 XML을 기대하고 있습니다.

당신의 질문에 관해서는

contentType: "application/json; charset=utf-8",
dataType: "json",

여기에서는 UTF8 문자 세트를 사용하여 json 데이터를 보내고 서버에서 json 데이터를 다시 기대합니다. dataType에 대한 JQuery 문서에 따라

json 유형은 페치 된 데이터 파일을 JavaScript 오브젝트로 구문 분석하고 생성 된 오브젝트를 결과 데이터로 리턴합니다.

So what you get in success handler is proper javascript object(JQuery converts the json object for you)

whereas

contentType: "application/json",
dataType: "text",

Here you are sending json data, since you haven't mentioned the encoding, as per the JQuery docs,

If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and since dataType is specified as text, what you get in success handler is plain text, as per the docs for dataType,

The text and xml types return the data with no processing. The data is simply passed on to the success handler


as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

참고URL : https://stackoverflow.com/questions/2722750/ajax-datatype

반응형