[英]How to post a HTML form using Javascript that has both “application/x-www-form-urlencoded” and “charset=UTF-8” in the Content-Type header
[英]HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
我正在嘗試使用 javascript 使用 ajax 到 spring Z594C103F2C6E004C3D8AB0E
$("#crear").click(function () {
var user = document.getElementById("user").value;
var client = document.getElementById("client").value;
var documents = document.getElementById("documents").value;
if (user==null||client==null||documents==null){
document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
alert('Rellene todo los campos!')
}
const data={
fecha_inicio:'A',
id:'A',
fecha_entrega:'A',
usuario:{
nombre:user
},
cliente: {
nombre:client
}
}
$.ajax({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
success: function(data) {
// ...
}
});
$.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
console.log('${data} and status is ${status}')
});
document.getElementById("error").innerHTML=user+client+documents;
});
和 java 代碼
@RequestMapping("/altas")
@RestController
public class AltaRestController {
private AltaController altaController;
public AltaRestController(AltaController altaController) {
this.altaController = altaController;
}
@PostMapping("/create-alta")
public void createAlta(@RequestBody AltaDTO altaDTO) {
altaController.createAlta(altaDTO);
}
我收到錯誤已解決 [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
當我使用 $.ajax 時它不發送任何請求,就在我使用 $.post 時它發送請求
問題似乎是您如何使用$.post
方法。 jQuery 默認使用application/x-www-form-urlencoded;charset=UTF-8
contentType on post 如果您不指定其他 contentType。 結合后端的 @RequestBody 注釋(默認需要application/json
),它會導致看到的異常和 415 狀態代碼。
這個問題的解決方案應該是相當簡單的,只需為 .post 方法添加正確的配置,如下所示:
$.post({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data)
})
.done((data, status) => {
console.log(data, status);
//do whatever you like with data and status
});
此外,如jQuery文檔中所述, $.post
.post 只是$.ajax
的簡寫方法,因此如果$.ajax
中的配置不正確,那么您應該如何配置該請求,或者如何配置$.post
你處理回調方法。 對我來說,主要懷疑是您在$.ajax
請求中指定的success
function ,檢查那里沒有問題,或者只是使用其他回調方法,如.done
、 .fail
和.always
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.