IT

XmlHttpRequest.responseJSON에서 JSON 구문 분석

lottoking 2020. 10. 9. 08:38

XmlHttpRequest.responseJSON에서 JSON 구문 분석


javscript에서 bit.ly JSON 응답을 구문 분석합니다.

XmlHttpRequest를 통해 JSON을 얻습니다.

var req = new XMLHttpRequest;  
req.overrideMimeType("application/json");  
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url)
          + BITLY_API_LOGIN, true);  
var target = this;  
req.onload  = function() {target.parseJSON(req, url)};  
req.send(null);

parseJSON: function(req, url) {  
if (req.status == 200) {  
    var jsonResponse = req.responseJSON;  
    var bitlyUrl = jsonResponse.results[url].shortUrl;  
}

나는 파이어 폭스 애드온을 보유한다. 실행하면 줄에 "jsonResponse is undefined"오류가 표시됩니다 var bitlyUrl = jsonResponse.results[url].shortUrl;. 여기서 JSON을 구문 분석하는 데 문제가 있습니까? 아니면 어떤 문제가 있습니까?


새로운 방법 I : fetch

TL; DR 동기 요청을 보내거나 이전 브라우저를 지원할 필요가없는 한이 방법을 권장합니다.

요청이 적이면 Fetch API사용하여 HTTP 요청을 보낼 수 있습니다 . fetch API는 promise 와 함께 작동하며 JavaScript에서 작업 플로를 처리하는 좋은 방법입니다. 이 접근 방식 fetch()에서는에서는 요청을 보내는 ResponseBody.json()응답을 구문 분석하는 데 사용합니다.

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

외국어 : Fetch API는 IE11과 Edge 12 및 13에서 지원되지 않습니다 . 그러나 polyfill이 있습니다.

새로운 방법 II : responseType

Londeren답변 에서 작성 했듯이 최신 브라우저의 responseType속성을 사용하여 예상되는 응답 형식을 정의 할 수 있습니다 . 그런 다음 response속성을 통해 구문 분석 된 응답 데이터에 액세스 할 수 있습니다 .

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

규격 : responseType = 'json'IE11에서는 지원되지 않습니다.

고전적인 방법

표준 XMLHttpRequest 객체에는 responseJSON속성 이 없으며 responseTextresponseXML. 요청에 대해 약간의 JSON으로 실제로 응답하는 한 responseText, JSON를 텍스트로 코드 포함해야 우리하므로 다음과 JSON.parse()같이 구문 분석하기 만하면 됩니다 .

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

접근 방식은 XMLHttpRequestJSON.

JSONHttpRequest

responseJSONJQuery보다 가벼운 솔루션 을 사용 하고 싶지만 JSONHttpRequest를 확인하는 것이 좋습니다. 일반 XMLHttpRequest를 똑같이 작동하지만와 responseJSON속성 도 계명 제공합니다 . 코드에서 변경해야하는 모든 것은 첫 번째 줄입니다.

var req = new JSONHttpRequest();

JSONHttpRequest는 JavaScript 객체를 JSON으로 보안 강화 기능도 제공합니다. 자세한 내용과 코드는 http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/ 에서 사용할 수 있습니다 .

전체 공개 : 저는 Pixels | 바이트의 소유자입니다. 내 펼쳐가 문제에 대한 좋은 해결책이라고 생각합니다. 링크를 제거하려는 의견을 애굽주세요.


접근 가능합니다. xhr.responseType = 'json';

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
xhr.responseType = 'json';
xhr.onload = function(e) {
  if (this.status == 200) {
    console.log('response', this.response); // JSON response  
  }
};
xhr.send();
  

responseType에 대한 문서


참고 : 나는 이것을 Chrome에서만 테스트했습니다.

그것은는 XMLHttpRequest ..에 프로토 타입 함수를 추가 XHR2 ,

XHR (1) 당신은 아마 교체 할 필요가 this.responsethis.responseText

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return JSON.parse(this.response);
},writable:false,enumerable:false});

xhr2에서 json을 반환하려면

xhr.onload=function(){
 console.log(this.responseJSON());
}

편집하다

arraybuffer또는 다른 응답 유형 과 함께 XHR을 사용하려는 경우 응답이 string.

어쨌든 json을 구문 분석 할 수없는 경우와 같이 더 많은 검사를 추가해야합니다.

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return (typeof this.response==='string'?JSON.parse(this.response):this.response);
},writable:false,enumerable:false});

사용하려면 jQuery를 포함해야한다고 생각합니다 responseJSON.

jQuery가 없으면 responseText로 시도하고 다음과 같이 시도 할 수 있습니다. eval("("+req.responseText+")");

업데이트 :에 대한 의견을 읽으십시오 eval.eval로 테스트 할 수는 있지만 작업 확장에는 사용하지 마십시오.

또는

사용 json_parse : 사용 하지 않습니다eval


FF 확장 용인 경우 nsIJSON을 사용 합니다.

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);

parseJSON: function(req, url) {
if (req.status == 200) {
  var jsonResponse = Components.classes["@mozilla.org/dom/json;1"]
      .createInstance(Components.interfaces.nsIJSON.decode(req.responseText);
  var bitlyUrl = jsonResponse.results[url].shortUrl;
}

웹 페이지 JSON.parse의 경우Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

참고 URL : https://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson