programing

XmlHttpRequest.responseJ로부터의 JSON 해석아들.

madecode 2023. 4. 1. 23:24
반응형

XmlHttpRequest.responseJ로부터의 JSON 해석아들.

javascript의 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 defined"라는 오류가 나타난다.var bitlyUrl = jsonResponse.results[url].shortUrl;여기서 JSON을 해석하는 것이 잘못되었습니까?아니면 이 코드에 무슨 문제가 있나요?

새로운 방법 I:fetch

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

요청이 비동기인 경우 Fetch API를 사용하여 HTTP 요청을 전송할 수 있습니다.fetch API는 약속과 함께 작동하며, 이는 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에서는 지원되지 않습니다.하지만, 폴리 매립지가 있습니다.

새로운 방법 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속성, 단지responseText그리고.responseXML당신의 요청에 JSON으로 비트가 응답하는 한,responseTextJSON 코드를 텍스트로 포함해야 합니다.따라서 할 일은 이 코드를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);

호환성:이 접근방식은 를 지원하는 모든 브라우저와 함께 사용할 수 있습니다.XMLHttpRequest그리고.JSON.

JSONHttpRequest(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();
  

대응 문서유형

주의: 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());
}

편집

을 XHR과 함께 arraybuffer 다음에 , 즉 반응 이 '아니다'인지 해야 합니다.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 응답처럼 할 수 .본문eval("("+req.responseText+")");

UPDATE: 코멘트를 읽어주세요.eval 로 할 수 만, 에서는 사용하지 말아 주세요.eval 。

또는

use json_module : 를 사용하지 않습니다.eval

nsIJ 사용FF 확장의 경우 SON:

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;
}

웹페의 use를 사용하세요.JSON.parseComponents.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

언급URL : https://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson

반응형