简体   繁体   English

如何使用 javascript fetch 将参数传递给 action 方法?

[英]How can i pass a parameters to action method using javascript fetch?

I'm using js fetch to call to an action method(in asp.net mvc), but I need to pass parameters to the method.我正在使用 js fetch调用操作方法(在 asp.net mvc 中),但我需要将参数传递给该方法。

How can I pass this data using fetch ?如何使用fetch传递这些数据?

I'm trying to use this code but the data didn't pass:我正在尝试使用此代码,但数据没有通过:

fetch(url, {
    data: { repositoryName: "dada" }
})
.then(() => {
   console.log("test");
});

According to the documentation second parameter shouldn't contain data property.根据文档,第二个参数不应包含data属性。

I guess you need to use body property(you can use JSON string, FormData or URLSearchParams here basing on your needs, see docs ):我猜您需要使用body属性(您可以根据需要在此处使用 JSON 字符串、 FormDataURLSearchParams ,请参阅文档):

fetch(url, {
    method: "POST",
    body: JSON.stringify({ repositoryName: "dada" })        
}).then(() => { ... })

Also in this simple example it's possible to simply use query string like this:同样在这个简单的例子中,可以简单地使用这样的查询字符串:

fetch(url + '?repositoryName=dada').then(() => { ... })

Note that GET requests cannot have body so if your MVC action is GET action then you have to use query strings like in my second example.请注意,GET 请求不能有正文,因此如果您的 MVC 操作是 GET 操作,那么您必须使用我第二个示例中的查询字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将JavaScript变量作为参数传递给JSF操作方法? - How to pass JavaScript variables as parameters to JSF action method? 如何使用@ url.Action使用JavaScript传递带有值的参数 - How to pass parameters with value using @url.Action using javascript 如何将控制器和动作参数传递给 Rails 3 中的 javascript 函数? - How do I pass the controller and action parameters to a javascript function in Rails 3? 如何将状态传递给动作以获取API? - How can I pass state to action to fetch API? 如何在获取请求中传递 POST 参数? - 反应本机 - How can I pass POST parameters in fetch request? - React Native 我无法使用addEventListener Javascript / Jquery将参数传递给函数 - I can not pass parameters to a function using addEventListener Javascript/Jquery 如何使用HTML或javascript将变量传递到action属性以进行下载(按钮/链接), - How can i pass a variable into action attribute for download (button/link) using HTML or javascript, 如何在 javascript fetch() 方法上传递带有 url 的变量? - How to pass a variable with url on javascript fetch() method? 如何将参数传递给 jQuery $.getJSON 回调方法? - How can I pass parameters to a jQuery $.getJSON callback method? 如何使用Excel VBA将变量参数传递给Javascript函数 - How can I pass variable parameters into a Javascript Function using Excel VBA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM