简体   繁体   中英

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:

21-12-12:::visits;45;;pageviews;344---22-10-10:::visits;71;;pageviews;34---15-01-11:::visits;4;;pageviews;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.

Any suggestions or better alternatives would be great. Please don't mention JSON though, I've just given up with that.

Thanks

JSON is the alternative and extremely easy since you are using PHP and 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).

In your PHP code you simply echo json_encode($arrayWithYourData); and the response argument of your AJAX success callback will contain the same object.

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.

Assuming you have the above string available in a variable named string, you can do:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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