javascript - 如何使用 "Fetch API"在javascript和c#之间传递数据?

标签 javascript c# json http fetch-api

我知道如何通过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);
    })

它显示:

createuser.exe asks me to input a password

createuser.exe asks me to input a password

createuser.exe asks me to input a password

该url的使用基于ajax。

我将 url 更改为“http://localhost:62177/WebService1.asmx?op=HelloWorld”,它显示:

createuser.exe asks me to input a password

我以为是响应成功,结果什么也没收到,结果显示:

createuser.exe asks me to input a password

然后我修改了返回数据的方式,现在是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/

相关文章:

json - 使用expressjs 设置 JSON 的 URL 基础

javascript - 如何加入npm命令?

javascript - AngularJS HTTP GET 请求有时返回的不是最新的数据集

javascript - div 标签未更新

c# - 如何处理添加到列表事件?

C# EF6 回滚更改,EntityState.Unchanged 错误

c# - session 无效,因为用户已注销

php - 使用不带 jQuery 的 XMLHttpRequest 将 JSON 数据发送到 PHP

javascript - 如何在 Chrome 中正确读取和修复 Web 应用程序的内存使用情况

javascript - 如何使用javascript仅删除字符串中的html标签