简体   繁体   中英

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.

[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next

To get these data, I would use jQuery.ajax() function. My code are as follow:-

function loadData(page){                
    $.ajax
    ({
        type: "POST",
        url: "http://sandbox.dev/favourite/test",
        data: "page="+page,
        success: function(msg)
        {
            $("#area").ajaxComplete(function(event, request, settings)
            {
                $("#area").html(msg);
            });
        }
    });
}

Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.

It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:

{
    "data": [
        {"name": "John Doe", "favourite": "cupcakes"},
        {"name": "Jane Citizen", "favourite": "Baked beans"}
    ],
    "pagination": {
        "prev": "previous page URL",
        "next": "next page URL"
    }
}

On client-side it can be parsed very easily:

$.ajax({
    url: "URL",
    dataType:'json',
    success: function(resp) { 
        // use resp.data and resp.pagination here
    }
});

put a dataType to your ajax request to receive a json object or you will receive a string.

if you put "previous" and "next" in your json..that will be invalid.

function loadData(page){                
    $.ajax({
        type: "POST",
        url: "http://sandbox.dev/favourite/test",
        data: {'page':page},
        dataType:'json',
        success: function(msg){ 
            if(typeof (msg) == 'object'){
              // do something... 
            }else{
              alert('invalid json');
            }
        },
        complete:function(){ 
           //do something
        }
    });
}

and .. in your php file, put a header

header("Content-type:application/json");
// print your json..

To see your json object... use console.log , like this:

// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}

Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/ )

{
    "paginate": {
        "previous": "http...previsouslink",
        "next": "http...nextlink"
    },
    "data": [
        {
            "name": "JohnDoe",
            "favourite": "cupcakes"
        },
        {
            "name": "JaneCitizen",
            "favourite": "Bakedbeans"
        }
    ]
}

Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next . I am guessing that the first object in your return url is for Previous and the next one is for Next . Simply return the below string...

[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]

and read it as under.

function loadData(page){                
    $.ajax
    ({
        type: "POST",
        url: "http://sandbox.dev/favourite/test",
        dataType:'json',
        success: function(msg)
        {
            var previous = msg[0];  //This will give u your previous object and
            var next = msg[1]; //this will give you your next object

            //You can use prev and next here.

            //$("#area").ajaxComplete(function(event, request, settings)
            //{
            //    $("#area").html(msg);
            //});
        }
    });
}

This way return only that data that's going to change not the entire html.

You can try this :-

var jsObject = JSON.parse(your_data);

data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

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