简体   繁体   English

如何使用正则表达式解析Ajax / Jquery响应数据?

[英]How do you parse Ajax/Jquery response data using regex?

my apologies if I used incorrect terms in my title. 如果标题中使用了不正确的用语,我深表歉意。 I am not sure how else to put this. 我不知道该怎么办。

I am using Ajax to make a GET call and it responds with data in the form of html/txt/json etc. all in one file. 我正在使用Ajax进行GET调用,并且它以html / txt / json等形式的数据进行响应,所有这些都在一个文件中。 I am trying to extract only whats in between [{ }]. 我试图仅提取[{}]之间的内容。

I have successfully used the regex below to achieve this using https://regexr.com : 我已经成功使用以下正则表达式通过https://regexr.com实现了这一点:

(?=\[\{).*(\}\])

On this response data returned by my GET call: 关于我的GET调用返回的响应数据:

Lots of random text, random html, etc. 
[{There is text in here hello world}]
Lots of random text, random html, etc.  

As you can see this regex will properly extract this: 如您所见,此正则表达式将正确提取此内容:

[{There is text in here hello world}]

This works great! 这很棒! But I just can't seem to figure out how to automatically parse the data after I get the response. 但是我似乎无法弄清楚在收到响应后如何自动解析数据。 I am currently trying: 我目前正在尝试:

$.ajax(settings).done(function (response) {
  console.log(response.replace(/(?=\[\{).*(\}\])/));
});

But this isn't working. 但这是行不通的。 Am I going at this completely wrong? 我会完全错误吗? It's only outputting the full GET response and not the regex data. 它仅输出完整的GET响应,而不输出正则表达式数据。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

If your response is a string, then you could use string.match() like this: 如果您的响应是字符串,则可以使用如下所示的string.match()

$.ajax(settings).done(function (response) {
  console.log(response.match(/(?=\[\{).*(\}\])/));
});

You could try using the .indexOf() to find the indices of { and } : 您可以尝试使用.indexOf()查找{}的索引:

var first_index = indexOf("{");

var second_index = indexOf("}"):

Once you find the indices, define a substring based on these indices: 找到索引后,请根据以下索引定义一个子字符串:

var parsed_string = response.substring(first_index + 1, second_index);

You will need to add 1 to the first_index variable so that you do not get the "{" in the parsed_string variable. 您将需要在first_index变量中加1,以免在parsed_string变量中获得"{"

jsfiddle 的jsfiddle

The more robust method would be to request the data in JSON, parse it accordingly then do javascript stuff with it: 更加健壮的方法是请求JSON中的数据,然后进行相应的解析,然后对其进行javascript处理:

var obj = JSON.parse(response);
// do js stuff with obj

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

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