我如何发布Ajax请求

时间:2018-07-07 12:16:06

标签: javascript jquery ajax

这是我第一次处理AJAX请求,并且我编写的代码有问题。

API数据如下:

"data": {
    "id": 5,
    "name": "Big Mac beef burger",
    "description": "Big Mac beef burger with tomato slices and mayoneez",
    "image": "http://spoon.mtech-ins.com/uploads/products/big_mac.jpg",
    "price": 100.52,
    "basic_price": true,
    "provider_name": "Mcdonald's Restaurant egypt",
    "has_offer": true,
    "discount": 20,
    "discount_price": 80.416,
    "favorite": false,
    "product_additions": [
        {
            "id": 1,
            "name": "Size",
            "required": true,
            "multiple": false,
            "product_addition_items": [
                {
                    "id": 1,
                    "name": "Small",
                    "price": 20
                },
                {
                    "id": 2,
                    "name": "Medium",
                    "price": 50
                }
            ]
        }
    ]
}

我只想在"Product_addition_items"嵌套的请求中添加"product_additions"

我的两个问题是:

  1. 如何将数据传递到此深度嵌套的数组(product_addition_items)

  2. 如何在请求正文中传递数组?

这是我写的代码:

$.ajax({
      type: 'POST',
      url: `http://spoon.mtech-ins.com/api/admin/v1/addAddition/5`,
      headers: {
        Authorization:
          'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9zcG9vbi5tdGVjaC1pbnMuY29tXC9hcGlcL2FkbWluXC92MVwvdXNlcnNMb2dpbiIsImlhdCI6MTUyOTU5NzU3NywiZXhwIjoxNTM3MzczNTc3LCJuYmYiOjE1Mjk1OTc1NzcsImp0aSI6IkY1azBEQkk1MEhrdm5saHEiLCJzdWIiOjE0OCwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.XKNfm6cxBQnfKaEDMxsVK0vTETzIp6uisA0UwB0Q2-Q'
      },
      data: {
        name: product.name,
        required: product.required,
        multiple: product.multiple,
        options: options
      },
      success: data => {
        console.log(data);
      },
      error: err => console.log(err)
    });

我确定这是错误的,因为它不起作用,但我不知道该怎么办

谢谢:)

2 个答案:

答案 0 :(得分:0)

您应该使用method键而不是type键。试试这个

$.ajax({
  method: 'POST',
  url: `http://spoon.mtech-ins.com/api/admin/v1/addAddition/5`,
  data: {
    name: product.name,
    required: product.required,
    multiple: product.multiple,
    options: options
  },
  success: function(data, status, xhr) {
    console.log(data);
  },
  error: function(err) {
    console.log(err);
  }
});

答案 1 :(得分:0)

要将数组传递给请求主体,您只需要调用带有响应参数的函数即可。响应参数会在成功请求后接收函数要接收的任何对象或值。

success: function (data) { // here data is the response parameter
                response($.map(data, function (eachData) {  //map is used to iterate each value if it contains a list or array
                    // do whatever you want to do with each data
                ))
            }