Home > Backend Development > PHP Tutorial > javascript - 数据解析问题

javascript - 数据解析问题

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:30:01
Original
1192 people have browsed it

<code>res({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})
</code>
Copy after login
Copy after login

一个API返回这种数据,应该怎么解析呢?用PHP 或者 js,比如我想得到 totalPage,要怎么写?

回复内容:

<code>res({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})
</code>
Copy after login
Copy after login

一个API返回这种数据,应该怎么解析呢?用PHP 或者 js,比如我想得到 totalPage,要怎么写?

类似于jsonp方式的请求返回的数据
1.如果使用了jquery类库,则可以直接采用jquery的ajax方式编码处理jsonp,比较简单。网上资料比较多,不再累赘。

2.如果是自己手动处理写的代码有点多,需要以下操作
第一步需要发送请求并将返回内容作为脚本注入

<code> var script = document.createElement('script');
 script.setAttribute('src', url);//此处的url即为请求的API
 // 把script标签加入head,发送请求
 document.getElementsByTagName('head')[0].appendChild(script);
</code>
Copy after login

第二步,在画面上定义res函数,此时res里面的data即为需要的object,可以在这个函数里面操作data

<code>function res(data1){
   ...//此时的data1即是{{"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]}}
}
</code>
Copy after login

第一种:
var string = 'res({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})';
var response = JSON.parse(string.substr(4,string.length-5));

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template