用jquery读取webservice的问题?
我的function有什么问题? 我想从我的webservice读取响应,但我收到一个错误。
浏览器消息是:
undefined- status:错误
当我按下按钮时,我只看到我的jQuery调用的错误function,但我不知道为什么。 请帮我。
function SetupCompanyInfo(companyID) { //alert('aaa'); companyID = '1'; $.ajax({ type: "POST", url: '../../../Services/CompanyServices.asmx/GetCompanyInfo', data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }); } function OnSuccess(data, status) { SetMainBody(data); } function OnError(request, status, error) { SetMainBody(error + '- ' + request + ' status:' + status); }
我的网络服务:
using System; using System.Web.Services; using System.Web.Script.Services; /// /// Summary description for CompanyServices /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] //[System.ComponentModel.ToolboxItem(false)] public class CompanyServices : System.Web.Services.WebService { [WebMethod] public string GetCompanyInfo() { string response = "aaa"; Console.WriteLine("here"); return response.ToString(); } [WebMethod] public string GetCompanyInfo(string id) { string response = "aaa"; Console.WriteLine("here2"+id); return response.ToString(); } }
我的aspx文件,head和我的按钮代码的一部分:
Cip在正确的路径上 – 你需要做出响应JSON,然后在客户端正确访问JSON。 您的ASMX方法应如下所示:
[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... }
而你的客户端JS成功函数应该访问这样的数据(你需要访问ASP.Net生成的JSON的d
属性):
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 }
当你通过ajax调用方法时,你也应该传入正确的参数。 就像是:
data: "{'id':'" + companyID + "'}",
看起来你的webservice只响应纯文本,而jQuery请求需要JSON作为回报。
JSON是一种允许您以连贯的方式发送不同数据类型(字符串,整数,数组等)的格式。 此页面上的注释18显示了人员列表的典型JSON响应。
您的回答应该类似于:
{"companyName": "Foobar Inc."}
并且,如果我没有弄错的话,你的onSuccess函数应该是这样的:
function OnSuccess(data, status) { SetMainBody(data.companyName); }
现在我不完全确定jQuery函数,但你的响应肯定不是JSON! 🙂
您的网络服务响应什么内容类型? 对于JSON响应,它应该是application/json
。
就像你使用它们一样,OnError和OnSucces是需要参数的函数。 也许首先尝试更简单的方法来获得更多反馈:
error: function(status, error) { alert(status + " - " + error); }