jquery post方法所需的Javascript函数



我的jQuery

let name = document.getElementById("Name").value;
let code = document.getElementById("Code").value;
let type = document.getElementById("ProductTypeId").value;
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "html",
data: json,
success: function(data){ 
//var message = data.Message; 
alert(data);
$('.CommentSection').html(data);
}
}

我需要使用fetch将jQuery转换为纯Javascript函数。这是一个带有html返回的post方法。可以使用fetch吗。

编辑:下面是我的Javascript的获取方法:

fetch(url + "?" + o)
.then(function (response) {
//check if it is redirected to custom error page
if (response.redirected && response.url.indexOf("/Error") > 0) {
response.text().then(function (html) {
debugger
window.location.href = response.url;
});
} else {
response.text().then(function (html) {
document.getElementById('view-all').innerHTML = html;
});
}
})
.catch(function (err) {
console.log('Fetch Error', err);
});

fetch还接受第二个参数,该参数是一个文字对象,包含与请求有关的信息,如请求方法、模式、标头和POST BODY。

直接来自Mozilla文档:

var data = { name: "justin", code: "SDF", type: "some-type" };
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

最新更新