[英]jQuery $.AJAX to replace with JavaScript fetch - mvc4 method arguments are always null
We had a working jQuery script which calls an MVC4 C# controller method like this:我们有一个有效的 jQuery 脚本调用 MVC4 C# controller 方法,如下所示:
// C# controller method
public ActionResult MyMethod(String text, String number)
{
... do something ...
... returns a partial view html result ...
}
// javascript call
var myData = { text:"something", number: "12" };
$.ajax({ url:ourUrl, type:"GET", data: myData,
success: function(data) { processAjaxHtml( data )}});
Now we want to replace this $.ajax call to a native fetch(...) call like this (and use a Promise):现在我们想将这个 $.ajax 调用替换为像这样的原生 fetch(...) 调用(并使用 Promise):
function startAjaxHtmlCall(url) {
var result = fetch( url, {method: "GET", body: myData});
return result.then( function(resp) { return resp.text(); });
}
starAjaxCall(ourUrl).then( resp => processAjaxHtml(resp) );
We have problems, and somehow we cannot find the answers:我们有问题,不知何故我们找不到答案:
Note: we tried this in Firefox and Chrome, the code is MVC5, C#, .NET Framework 4.5 (not.CORE.) hosted by IIS.注意:我们在 Firefox 和 Chrome 中尝试了这个,代码是 MVC5, C#, .NET Framework 4.5 (not.CORE.) hosted by IIS。
We changed the javascript call as the following (and everything works again):我们将 javascript 调用更改为以下内容(并且一切再次正常):
var promise = new Promise((resolve, reject) => {
$.ajax({
url: url,
method: method,
data: myData,
success: function(data) { resolve(data); },
error: function(error) { reject(error); },
});
});
return promise;
// note: .then( function(resp) { return resp.text(); }) // needs no more
So: what do we wrong?那么:我们做错了什么? what is the information we do not know, do not understand about fetch?
什么是我们不知道、不了解fetch的信息? How to replace $.ajax to fetch in this situation correctly?
在这种情况下如何正确替换 $.ajax 以获取? can it works with GET again?
它可以再次与 GET 一起使用吗? how to modify the controller method to receive the arguments?
如何修改controller方法接收arguments?
GET requests do not have a BODY, they have querystring parameters. GET 请求没有 BODY,它们有查询字符串参数。 Using URLSearchParams makes it easy
使用URLSearchParams使它变得简单
var myData = { text:"something", number: "12" };
return fetch('https://example.com?' + new URLSearchParams(myData))
.then( function(resp) { return resp.text(); })
Other way of building the URL构建 URL 的其他方式
const url = new URL('https://example.com');
url.search = new URLSearchParams(myData).toString();
return fetch(url)...
If you were planning on sending JSON to the server with a post request如果您计划通过 post 请求将 JSON 发送到服务器
fetch('https://example.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(myData)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.