简体   繁体   English

我怎样才能最容易地将这个 HTTP 响应解析为 JSON 然后访问 responseText 字段?

[英]How can I most easily parse this HTTP response into JSON to then access responseText fields?

I'm trying to parse the plaintext that's returned from this URL -- https://www.cloudflare.com/cdn-cgi/trace -- in order to read the IP address value.我正在尝试解析从此 URL - https://www.cloudflare.com/cdn-cgi/trace返回的明文 - 以读取 ZA12A3079E14CED46E69BA52B 地址值。 This is the code snippet I'm using for the request:这是我用于请求的代码片段:

 ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) { return data; });

When logged in browser console, the response looks like the following:登录浏览器控制台后,响应如下所示:

在此处输入图像描述

I've tried using JSON.stringify() , accessing responseText using ['responseText'] , as well as .responseText .. but no luck.我试过使用JSON.stringify() ,使用['responseText']访问responseText ,以及.responseText .. 但没有运气。

How can this response be parsed so that I can most easily access the ip value from within responseText ?如何解析此响应,以便我可以最轻松地从responseText中访问ip值?

$.get("https://www.cloudflare.com/cdn-cgi/trace", function(data) {
  const [ ,ip ] = data.match(new RegExp("ip=" + "(.*)" + "\n"));
  console.log(ip);
});

Outputs输出

"2a01:cb18:362:2200:e90e:fb09:8445:6302"

You can either parse on carriage return or simply look for the ip= in the string or use a regex search it.您可以在回车上进行解析,也可以简单地在字符串中查找 ip= 或使用正则表达式搜索它。

If you look at ipAddress.reponseText it's a carriage return delimited string.如果您查看 ipAddress.reponseText 它是一个回车分隔的字符串。 so所以

var myip=ipAddress.responseText.split('\n');
console.log(myip[2]); 'the text ip=192.168.1.10  for example if it's always in the same position.  

If it's not in the same position then look through the array to find it.如果它不在同一个 position 中,则查看数组以找到它。

its return document as response, so i'm not pretty clear about JSON, here some way它的返回文件作为响应,所以我不太清楚 JSON,这里有一些方法

 const ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function (data) { const arr = data.split("\n") const ip = arr.filter(v => v.includes("ip="))[0] console.log(ip.split("=")[1]) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM