Problem reading webservice with jquery?

后端 未结 4 1246
春和景丽
春和景丽 2021-01-16 20:04

What\'s my function\'s problem? I want to read the response from my webservice but I just receive an error.

The browser message is:

undefined-

相关标签:
4条回答
  • 2021-01-16 20:09

    It seems like your webservice only responds with plain text, while the jQuery request expects JSON in return.

    JSON is a format that lets you send different datatypes (strings, integers, arrays, etc.) in a coherent manner. Note 18 on this page shows you a typical JSON response for a person listing.

    Your response should look something like:

    {"companyName": "Foobar Inc."}
    

    And, if I'm not mistaken, your onSuccess function should be something along the lines of:

    function OnSuccess(data, status) {
    SetMainBody(data.companyName);
    }
    

    Now I'm not entirely sure about the jQuery function, but your response is definitely not JSON! :-)

    0 讨论(0)
  • 2021-01-16 20:15

    Like you use them your OnError and OnSucces are functions that need parameters. Maybe try something simpler like this first to get more feedback:

    error: function(status, error) { alert(status + " - " + error); }
    
    0 讨论(0)
  • 2021-01-16 20:19

    What Content-Type does your webservice respond with? It should be application/json for a JSON response.

    0 讨论(0)
  • 2021-01-16 20:22

    Cip was on the right path - you need to make the response JSON, and then properly access the JSON on the client side. Your ASMX method should look like this:

    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)] // <--- To make it JSON
    public string GetCompanyInfo(string id)     
    {         
        Console.WriteLine("here2"+id);         
        return "aaa"; //never call "ToString()" on a string...
    } 
    

    And your client side JS success function should access the data like this (you need to access the d property for JSON generated by ASP.Net):

    function OnSuccess(data, status) { 
         SetMainBody(data.d);  //"d" is the js object representation of the return 
                               //value from the web method. In your case it's just
                               //a string, but it could be a more complex object 
                               //or an array
    }  
    

    When you call the method via ajax, you should pass in the right arguments as well. Something like:

    data: "{'id':'" + companyID + "'}", 
    
    0 讨论(0)
提交回复
热议问题