Epulari
Epulari

Reputation: 59

How to use "Fetch API" to pass data between javascript and c#?

I know about how to pass data between javascript and c# by ajax, and now I want to know 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);
    })

it showed:

createuser.exe asks me to input a password

createuser.exe asks me to input a password

createuser.exe asks me to input a password

The usage of this url is based on ajax.

I changed the url to "http://localhost:62177/WebService1.asmx?op=HelloWorld", it showed:

createuser.exe asks me to input a password

I thought it was response success, however I received nothing and it showed:

createuser.exe asks me to input a password

Then I modified the method of return data, now it was json-format :

c#:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public void HelloWorld()
{
    object JSONObj = JsonConvert.SerializeObject("Hello World");
    Context.Response.Write(JSONObj);
}

But there was no change.

I don't know how else to change it. Can someone give me a little help?

Upvotes: 2

Views: 1389

Answers (2)

PunchUpward33
PunchUpward33

Reputation: 11

The output of your web service doesn't produce JSON. It outputs "Hello World" when it should say something like:

{"YourKeyHere":"Hello World"}

I'd change the web service code to something like this:

    [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);
    }

At the top of your web service, uncomment this decoration: [System.Web.Script.Services.ScriptService]. It needs to be uncommented so that JavaScript (and maybe other clients) can see your service.

In your JavaScript, your response will come back as text (not json), and it will come with a {"d":null} bracket appended to it. To clean this up, I used substrings and placed them in a different function:

    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

    }

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370879

You first need to make sure that your server is returning something in JSON format. But in addition, in your JS, you have to return the response.json() (or the response.text() or whatever method is appropriate) infetch` so that the stream can be processed, so that you can get a response in the next function:

fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
  .then(response => {
    return response.json();
  })
  .then(responseJSON => {
    alert(responseJSON);
  })

The initial response is a response stream object, which doesn't actually contain any data yet.

Upvotes: 0

Related Questions