简体   繁体   English

如何为JSON API创建复杂的javascript对象

[英]How to create complex javascript object for JSON API

Below is the structure of JSON which I use to query an API 下面是我用来查询API的JSON结构

"order_items": [
        {
            "menu_item_id": "VD1PIEBIIG", 
            "menu_item_name": "Create Your Own", 
            "modifiers": [
                {
                    "modifier_id": "6HEK9TXSBQ", 
                    "modifier_name": "Shrimp"
                }
            ], 
            "quantity": "1", 
            "total": 15.99, 
            "variant_id": "TXDOR7S83E", 
            "variant_name": "X-Lg 18\""
        }
    ]

Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). 现在我想使用Javascript从HTML页面调用此API(使用HTML元素,如表单和下拉菜单等)。 I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. 我想创建一个具有适当结构的Javascript对象,然后使用“stringify”函数将其转换为JSON。 But I am not able to create the Javascript object. 但我无法创建Javascript对象。 Can anyone help with this? 有人能帮忙吗?

Like i want to have the following structure 就像我想要有以下结构

obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";

and so on. 等等。

var jsonToSend = { "order_items": [ ] };

// then for each order item
var orderItem = { "menu_item_id": <whatever>, 
  "menu_item_name": <whatever>,
  "quantity": <whatever>,
  "total": <whatever>,
  "variant_id": <whatever>,
  "variant_name": <whatever>,
  "modifiers": []
};

// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);

jsonToSend.order_items.push(orderItem);

JSON.stringify(jsonToSend);

Well there are a couple of ways to do this. 那么有几种方法可以做到这一点。

  • Manually create the Json object to send from the HTML elements: 手动创建要从HTML元素发送的Json对象:

      $.ajax({ type: "POST", url: "some.php", data: new {"order_items": [ { "total": $('total').Val(), "variant_id": $('variant_id').Val(), "variant_name": $('variant_name').Val() } ]}) .done(function( msg ) { alert( "Data Saved: " + msg ); }); 
  • You could use a great framework like KnockoutJs , this will keep your JSON object up to date with your form, so that you don't have to do it manually. 您可以使用像KnockoutJs这样的优秀框架,这将使您的JSON对象与您的表单保持同步,这样您就不必手动完成。 When you are ready you just submit your original json back to the server. 准备就绪后,只需将原始json提交回服务器即可。

See this basic example on JsFiddle JsFiddle上查看这个基本示例

    var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);

    this.registerClick = function() {
        this.numberOfClicks(this.numberOfClicks() + 1);
    };

    this.resetClicks = function() {
        this.numberOfClicks(0);
    };

    this.hasClickedTooManyTimes = ko.computed(function() {
        return this.numberOfClicks() >= 3;
    }, this);
};

ko.applyBindings(new ClickCounterViewModel());
  • You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right. 您可以使用任意数量的插件来序列化表单,但问题是使JSON结构恰到好处。

See SerializeArray 请参见SerializeArray

$( "form" ).submit(function( event ) {
      console.log( $( this ).serializeArray() );
      event.preventDefault();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM