我知道如何通过ajax在javascript和c#之间传递数据,现在我想知道fetch。
c#:
namespace WebApplication1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
JavaScript:
fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
.then(response => {
alert(response.json());
})
.then(response => {
alert(response);
})
它显示:
该url的使用基于ajax。
我将 url 更改为“http://localhost:62177/WebService1.asmx?op=HelloWorld”,它显示:
我以为是响应成功,结果什么也没收到,结果显示:
然后我修改了返回数据的方式,现在是json-format:
c#:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public void HelloWorld()
{
object JSONObj = JsonConvert.SerializeObject("Hello World");
Context.Response.Write(JSONObj);
}
但是没有任何变化。
我不知道还有什么办法可以改变它。有人可以帮我一点忙吗?
最佳答案
您的网络服务的输出不生成 JSON。它输出 "Hello World"
当它应该说这样的话时:
{"YourKeyHere":"Hello World"}
我会将 Web 服务代码更改为如下内容:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat System.Web.Script.Services.ResponseFormat.Json)]
public void HelloWorld()
{
var obj = new { YourKeyHere = "Hello World" };
string JSONObj = JsonConvert.SerializeObject(obj);
Context.Response.Write(JSONObj);
}
在您的 Web 服务顶部,取消注释此装饰:[System.Web.Script.Services.ScriptService]
。它需要取消注释,以便 JavaScript(可能还有其他客户端)可以看到您的服务。
在您的 JavaScript 中,您的响应将以文本(而非 json)形式返回,并且会附加一个 {"d":null}
括号。为了清理它,我使用了子字符串并将它们放在不同的函数中:
function SayHello()
{
//...
var options = {
method: 'GET' ,
headers: {
'Content-Type': 'application/json',
}
};
fetch("http://localhost:62177/WebService1.asmx/HelloWorld", options)
// Handle success
.then(response => response.text())
.then(result => DisplayResponse(result))
.catch(err => console.log('Request Failed', err));
//...
}
function DisplayResponse(result) {
console.log(result); //not sure why 'd:null' shows in output
console.log(result.substring(0, result.indexOf('{"d":null}'))); //get rid of 'd:null'
console.log(JSON.parse(result.substring(0, result.indexOf('{"d":null}')))); //get rid of 'd:null' then parse
}
关于javascript - 如何使用 "Fetch API"在javascript和c#之间传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594225/