简体   繁体   中英

fetch JSON data using jQuery and validate it

I have been using jQuery lately, but never used JSON with it.

Now, I am preparing JSON using PHP on server-side. I need to fetch that JSON data using javascript (preferred way using jQuery)

I can get JSON data by going to similar URL mentioned below

http://www.example.com/getjson.php?catid=1        
                    OR
http://www.example.com/getjson.php?catid=15       

There is a file name "getjson.php" on my server, which will accept a 'get' argument as catid (stands for category id), fetches data from category table, and output data in JSON format.

Now I need JS code (If code would be in jQuery, it would be added advantage as I badly need code in jQuery) which can fetch data from above mentioned URL, and parse it (which I believe is decoding JSON, right?).

One more thing, after fetching data, I need to validate whether data that I have received is in JSON format or not (It's really important)

Category Table have following fields, which I am outputing in JSON format.

ID, Name, Description, ImageURL, Active, Deleted

Please help me out. Thanks.

You can use a JQuery get function to request your server page and pass the relevant parameters.

Then to parse your response you can use JSON.parse() , if it returns/throws an error you don't have valid JSON.

NOTE once your response has been run through JSON.parse it wont be json string any more it will be a JavaScript object.

$.ajax({
    dataType: 'json',
    type: 'GET',
    url: 'http://www.example.com/getjson.php?catid=15',
    success: function(data) {
        // data be a javascript object that contains your already decoded json data
    }
});

Use $.getJSON(url, data, callback);

It get data from the given url and check if it is JSON valid.

$.getJSON(
    'http://www.example.com/getjson.php?catid=' + $('#valueContainer').val(),
     function (data) {
         // do stuff here
     });

You can use the following to retrieve the JSON:

$.getJSON('http://www.example.com/getjson.php?catid=1', function(data) { // success statement here });

Then, you can use jQuery.parseJSON() to verify the result. See http://api.jquery.com/jQuery.parseJSON/ for more details.

$.getJSON should do the trick.

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){
    console.log( data ); // display the JSON data in the web console
});

Because $.getJSON returns a jqXHR object you can attach an error callback as follows:

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){
    console.log( data ); // display the JSON *data* in the web console
    // you can then access the params via dot syntax like this:
    var id = data.ID,
        name = data.Name,
        description = data.Description,
        imageURL = data.ImageURL,
        active = data.Active,
        deleted = data.Deleted;
}).error(function(){
     alert("Error!");
});

Fun fact: Whenever you use jQuery for AJAX it adds an X-Requested-With header with the value "XMLHttpRequest" to the request. You can check for this header with your server-side PHP code and decide if you should display an HTML page or send back AJAX-appropriate data instead.

This is useful when you bind to the click event on a link. But you want the link to still work when someone navigates directly to the href.

<a href="http://www.example.com/getjson.php?catid=1">Category 1</a>    

JS:

$("a").click(function(e){
    // Keep the browser from navigating to the link's href.
    e.preventDefault();

    // Because we are using one of jQuery's AJAX methods we can get data back from 
    // our server that is different than the data we would get if we navigated to
    // the link directly.
    $.getJSON(this.href, /* optional data param */ function(data){
        console.log( data ); // display the JSON data in the web console
    });
});

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