Javascript-data parsing

Source: Internet
Author: User
{Code...} How should I parse the data returned by an API? PHP or js is used. For example, if I want to get totalPage, how can I write it?
res({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})

How should I parse the data returned by an API? PHP or js is used. For example, if I want to get totalPage, how can I write it?

Reply content:
res({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})

How should I parse the data returned by an API? PHP or js is used. For example, if I want to get totalPage, how can I write it?

Similar to the data returned by a jsonp request
1. If the jquery class library is used, jsonp can be directly encoded using jquery ajax, which is relatively simple. There are a lot of online materials and it is no longer cumbersome.

2. If you manually write more code, perform the following operations:
The first step is to send a request and inject the returned content as a script.

Var script = document. createElement ('script'); script. setAttribute ('src', url); // The url here is the requested API // Add the script tag to the head and send the request document. getElementsByTagName ('head') [0]. appendChild (script );

Step 2: Define the imageresFunction. In this case, the data in res is the required object. You can operate data in this function.

Function res (data1 ){... // at this time, data1 is {"total": 100, "totalPage": 10, "page": 2, "items": ["data"]}

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.