JQuery和JSON [英] JQuery and JSON

查看:71
本文介绍了JQuery和JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要学习和做的事情。我有一个JSON文件,其中包含我的产品和详细信息(大小,颜色,描述)。在网站上我不能使用PHP和MySQL,我只能使用Javascript和HTML。现在我想要发生的是使用JQuery我可以读取和写入一个JSON文件(JSON文件将作为我的数据库)。我不确定是否只能使用JQuery和JSON。

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. 首先,如何查询JSON文件? (例如:我会搜索产品的名称和颜色。)

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

如何解析搜索到HTML的JSON数据?

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

如何将产品细节,产品添加到JSON文件中?

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.

我是JQuery和JSON的新手。

I'm new to both JQuery and JSON.

谢谢!

推荐答案

由于Javascript是客户端,因此无法使用仅使用Javascript写入服务器上的JSON文件。为了做到这一点,你需要一些服务器端代码。

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.

但是,读取和解析JSON文件不是问题。您可以使用 jQuery.getJSON 功能。您将提供url和callback参数(不需要数据,因为您正在读取文件,因此无需发送数据)。 url将是您的JSON文件的路径,回调将是一个使用数据的函数。

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.

以下是您的代码可能是什么样子的示例。我不确切知道你的JSON是什么,但是如果你有一个名为products的集合,其中包含一组带有详细信息name和price的对象,那么这段代码将打印出来:

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!
        });
    }, 
);

基本上,$ .getJSON中的数据变量使得JSON的全部内容可供您使用,非常容易。并且$ .each用于循环一组JSON对象。

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.

这篇关于JQuery和JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆