2

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?

3
  • doesn't look like you've set the server to send JSON at all - so of course you'll get errors trying to parse JSON Commented Apr 1, 2018 at 2:27
  • how to pass data between javascript and c# by ajax ... does your "ajax" code use JSON? I mean, the server side code in the ajax method that you say you know, is the same regardless, right. So, does your "ajax" method use JSON.parse? Commented Apr 1, 2018 at 2:29
  • The page for System.Web.Services.WebService states, "[d]efines the optional base class for XML Web services". XML is not JSON. Use the Network tab in Developer Tools to look at the raw response and see what is being returned. Commented Apr 1, 2018 at 2:35

2 Answers 2

1

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

    }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

the error would suggest that the server isn't responding with JSON
object JSONObj = JsonConvert.SerializeObject("Hello World"); Context.Response.Write(JSONObj); This is the server's return method, and it is in json format. However, it still get an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.