简体   繁体   English

如何使用在JQuery或JavaScript中从PHP回显的数据?

[英]how to use this data echoed from PHP in JQuery or JavaScript?

I have an AJAX request on a php file, which returns some data, like this: 我在php文件上有一个AJAX请求,它返回一些数据,如下所示:

21-12-12:::visits;45;;pageviews;344---22-10-10:::visits;71;;pageviews;34---15-01-11:::visits;4;;pageviews;30 21-12-12 :::访问; 45个;;浏览量; 344 --- 22-10-10 :::访问; 71个;;浏览量; 34 --- 15-01-11 :::访问; 4; ;网页浏览; 30

Notice the pattern^^ It's like a multidimensional array, but only not an array, just a string. 注意模式^^这就像一个多维数组,但不是数组,只是字符串。

I need a way to separate that string, and use the value of visits and pageviews for each date. 我需要一种方法来分隔该字符串,并使用每个日期的访问量和综合浏览量值。

I already know how to split the string up in JQuery, but i have no idea how to get the value of visits for a specific date from that string, example, get the number of visits for the date 15-01-11. 我已经知道如何在JQuery中拆分字符串,但是我不知道如何从该字符串获取特定日期的访问值,例如,获取日期15-01-11的访问次数。

Any suggestions or better alternatives would be great. 任何建议或更好的选择将是很好。 Please don't mention JSON though, I've just given up with that. 请不要提及JSON,我已经放弃了。

Thanks 谢谢

JSON is the alternative and extremely easy since you are using PHP and jQuery. JSON 替代方法,并且非常简单,因为您正在使用PHP和jQuery。 Actually, everything else would be either a huge mess (parsing a string like you want to do) or much more complicated (using XML instead of JSON). 实际上,其他所有事情要么是一团糟(按照您的意愿解析一个字符串),要么会变得更加复杂(使用XML而不是JSON)。

In your PHP code you simply echo json_encode($arrayWithYourData); 在您的PHP代码中,您只需echo json_encode($arrayWithYourData); and the response argument of your AJAX success callback will contain the same object. 并且AJAX成功回调的响应参数将包含相同的对象。

Since you want to get data for a certain date, you might want to use the data as the array key - then you can just use eg response['01-01-01'] to access the corresponding array element. 由于您要获取某个日期的数据,因此您可能希望将数据用作数组键-然后,您可以使用例如response['01-01-01']来访问相应的数组元素。

Assuming you have the above string available in a variable named string, you can do: 假设您在名为string的变量中具有上述字符串,则可以执行以下操作:

var parts = string.split('---'), visits = 0, pageviews = 0;
for(var i=0; i<parts.length; i++) {
  if(parts[i].indexOf('01-01-01')!=-1) { // ex: looking up 01-01-01
    parts = parts[i].split(':::')[1];
    parts = parts.split(';;');
    visits = parts[0].split(';')[1]; // visits for 01-01-01
    pageviews = parts[1].split(';')[1]; // pageviews for 01-01-01
  }
}

Do you have control over the output format? 您可以控制输出格式吗? If so switch to JSON, otherwise split the data with some RegEx. 如果是这样,请切换到JSON,否则请使用一些RegEx拆分数据。

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

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