我想用一些自定义字段向 rest api 发送一个帖子请求。这是我的代码
let newCharacter = {
'title': $('.create-char-name').val(),
'acf': {
'char_class': $('#char-class').val(),
'char_subclass': $('#char-subclass').val(),
'char_level': $('#char-level').val()
},
'status': 'publish'
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: newCharacter,
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
请求顺利通过,但当我检查json时,"acf "字段返回false。acf到wp api插件如果这些信息是有用的。
我找到的关于这个问题的唯一信息是 此职位但我不太明白这个答案是什么意思。我试着加上 xhr.setRequestHeader('Content-Type', application/json);
(我也试过用小写的首字母),在nonce下面,就像帖子中建议的那样,但是会返回这个错误。
"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"
试试下面这样的代码。
function NewCharacter(){
this.title;
this.acf;
this.status;
}
function CharInfo(){
this.char_class;
this.char_subclass;
this.char_level;
}
var charInfo = new CharInfo();
charInfo.char_class=$('#char-class').val();
charInfo.char_subclass=$('#char-subclass').val();
charInfo.char_level=$('#char-level').val();
var newCharacter = new NewCharacter();
newCharacter.title=$('.create-char-name').val();
newCharacter.acf=charInfo
newCharacter.status="publish";
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: JSON.stringify(newCharacter),
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
是的,我是有点笨。我试过 另一个插件 来做acf和rest api之间的桥梁,结果成功了。
我曾多次想到要尝试另一个插件,但我认为 "他们做的是同样的事情,没必要尝试那个"。这说明,你不应该随便刷掉那些看起来太明显或愚蠢的解决方案。