使用JQuery PATCH进行部分更新 [英] Using JQuery PATCH to make partial update

查看:67
本文介绍了使用JQuery PATCH进行部分更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我的URL(example.com/api/content/12)以以下格式返回JSON数据:

Alright, my URL(example.com/api/content/12) returns JSON data in the following format:

{
    "title" : "My blog post",
    "body" : "Body",
    "data" : "old"
}

我只想仅对数据字段进行更改.目前,我使用的是PUT,基本上只是替换整个东西,我意识到这是没有效率的.像这样:

I want to simply make a change to the data field only. Currently, I am using PUT and basically just replacing the whole thing, which I realize is ineffecient. Something like this:

var data = {
    "title" : "My blog post",
    "body" : "Body",
    "data" : "New data"
}

$.ajax({
   url: 'http://example.com/api/content/12',
   data: data,
   error: function() {
      console.log('Error');
   },
   dataType: 'json',
   success: function(data) {
      console.log('success');
   },
   type: 'PUT'
});

如何通过PATCH做到这一点?我真的不需要发送标题和正文字段,因为它们不会更改.我只想更新数据字段.

How do I do this with PATCH? I dont really need to send the title and body fields as they do not change. I just want to update the data field.

推荐答案

对于指定的用例,最简单的方法是使用

For the specified use case the simplest approach is to use JSON Merge Patch like so:

var patch = {
    "data" : "New data"
}

$.ajax({
   type: 'PATCH',
   url: 'http://example.com/api/content/12',
   data: JSON.stringify(patch),
   processData: false,
   contentType: 'application/merge-patch+json',

   /* success and error handling omitted for brevity */
});

processData:false data:JSON.stringify(patch)覆盖jQuery的PATCH默认序列化(不是JSON),并强制进行JSON序列化.

processData: false and data: JSON.stringify(patch) overrides jQuery's default serialization for PATCH (which isn't JSON) and forces JSON serialization.

请注意,JSON合并补丁具有固有的局限性(例如,您不能仅更新数组中的某些元素,无法将键设置为 null 等),因此对于更复杂的实现,我会鼓励OP考虑 JSON补丁:

Note that JSON Merge Patch has inherent limitations (e.g. you cannot update only some elements in an array, there is no way to set keys to null etc.), so for more complex implementations I would encourage the OP to consider JSON Patch:

var patch = [
    { "op": "replace", "path": "/data", "value": "New data" },
]

$.ajax({
   type: 'PATCH',
   url: 'http://example.com/api/content/12',
   data: JSON.stringify(patch),
   processData: false,
   contentType: 'application/json-patch+json',

   /* success and error handling omitted for brevity */
});

这篇关于使用JQuery PATCH进行部分更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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