开发者

JQuery and JSON

开发者 https://www.devze.com 2022-12-08 09:48 出处:网络
Here\'s something I want to learn and do. I have a JSON file that contains my product and details (size,开发者_如何学编程 color, description). In the website I can\'t use PHP and MySQL, I can only use

Here's something I want to learn and do. I have a JSON file that contains my product and details (size,开发者_如何学编程 color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.

  1. First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)

  2. How to parse the JSON datas that were searched into an HTML?

  3. How to add details, product to the JSON file?

It will also be great if you can point me to a good tutorial about my questions.

I'm new to both JQuery and JSON.

Thanks!


Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.

Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.

Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:

$.getJSON("getProductJSON.htm",
    function(data) {
        $.each(data.products, function(i, item) {
            var name = item.name;
            var price = item.price;
            // now display the name and price on the page here!
        });
    }, 
);

Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消