将json存储为变量以在另一个函数中重用 [英] Storing json as variable for reuse within another function

查看:108
本文介绍了将json存储为变量以在另一个函数中重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习jQuery,我想了解如何重用ajax json数据而无需再次发出请求.

I am learning jQuery and I would like to find out how to re-use ajax json data without having to make a second request.

例如

类别选择框:

<select id="Categories">
    <option value="Vegetables">Vegetables</option>
    <option value="Fruits">Fruits</option>
</select>

使用jQuery("#Categories").change(function(){...更改类别时,ajax调用get请求将拉出以下ajax数据.

When the Category is changed using jQuery("#Categories").change(function(){..., an ajax call get request pulls the following ajax data.

[{"Id":"1","Item":"Apples","PricePerKilo":"10.00"},
 {"Id":"3","Item":"Oranges","PricePerKilo":"12.00"}]

然后更新产品"选择框,如下所示:

And then the Products select box is updated as follows:

<select id="Products">
     <option value="1">Apples</option>
     <option value="3">Oranges</option>
</select>

现在我要做的是有一个用于输入所需重量的输入框.这样,当输入#weight的值更改时,总标签也将使用价格进行更新.

Now what I want to do, is have an input box for the required weight. That way, when the value of the input #weight is changed, a total label will also get updated with the price.

jQuery('#weight').bind('input', function() { 
   jQuery("#total").text( "£ " + (jQuery('#weight').val() * SOMETHING ).toFixed(2) ); 
)};

请注意...这应该类似于...

Note the SOMETHING... This should be something like...

data.PricePerKilo WHERE data.Id = jQuery("#products").val();

关于如何使json数据可重用的任何想法?

Any ideas on how to make the json data reusable?

推荐答案

您可以使用 .data() .在获取JSON之后,使用以下内容进行存储:

You can associate arbitrary data with a DOM element with .data(). Use the following to store it, after fetching the JSON:

jQuery("#products").data('productData', myData);

然后使用以下代码检索它:

Then retrieve it with this:

var myData = jQuery("#products").data('productData');

这篇关于将json存储为变量以在另一个函数中重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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