你好,我正试图在react 中发出get请求
使用JQuery,我曾经做过类似于的事情
$.get("Run",{ pr: "takeData", name: "Bob"}, function (o) {
console.log(o)
});
我试着做一些类似的事情
fetch("https://localhost:44347/Run?{
pr:"takeData",
name:"Bob"
}) .then( res => res.text())
.then((data) => {
console.log(data);
});
但id没有起作用,相反,我不得不像这个一样做
fetch("https://localhost:44347/Run?pr=takeData&name='Bob'") .then( res => res.text())
.then((data) => {
console.log(data);
});
它起了作用,但我不知道如何通过";pr";以及";name";无需直接在url中键入参数,有人能帮我吗?
您可以创建URL和URLSearchParams对象来创建请求,而无需手动在URL中写入字段。
var url = new URL("https://localhost:44347/Run");
url.search = new URLSearchParams({ pr: "takeData", name: "Bob"});
fetch(url).then( res => res.text())
.then((data) => {
console.log(data);
});
您可以使用模板文字,如下所示:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
这里有一个例子:
const myString = `https://localhost:44347/Run?pr=${varPr}&name=${varName}`
另一种方法是添加这样的字符串:
const myString = "https://localhost:44347/Run?pr=" + varPr + "&name=" + varName