2011-04-06 86 views
0

我试图使用下面的代码从web服务器(test.asmx.cs)中检索数据,但不知何故,这总是把错误给我...有谁知道它出了什么问题?无法使用ajax调用web服务器来获取返回结果.net c#

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Services; 

namespace Test 
{ 
    /// <summary> 
    /// Summary description for autocomplete 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService] 
    public class autocomplete : System.Web.Services.WebService 
    { 

     [WebMethod] 
     public string HelloWorld() 
     { 
      return "Hello World"; 
     } 

     [WebMethod] 
     public static string streetNameSearch(int id) 
     { 

      return "Melbourne|North Melbourne|South Melbourne|Richmond|North Richmond"; 
     } 
    } 
} 

而下面的jQuery代码已经把pgTest.aspx

$("#example").keyup(function() { 
    $.ajax({ 
     type: "POST", 
     url: "pgTest.aspx/streetNameSearch", 
     data: '{"id":"' + 1 + '"}', 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 
      var returnData = data.d; 
      alert(returnData) 

    }, 
    error: function (xhr, ajaxOptions, thrownError) { 
     alert(ajaxOptions); 
    }, 
    timeout: function (data) { 
     alert("time out"); 
    } 
}); 
}); 

enter image description here

+0

正在抛出的错误是什么? – jon3laze 2011-04-06 03:18:04

+0

@ jon3laze:错误只是'错误', – 2011-04-06 03:24:21

+0

在你的方法streetNameSearch中放置一个断点并检查它是否被调用? – 2011-04-06 03:34:56

回答

1

取消注释该行:

// [System.Web.Script.Services.ScriptService] 

的ScriptService属性使所有的ASMX服务的方法与生JSON响应。

0

下试试这个

 public static JsonResult streetNameSearch(string id) 
     { 

      return Json("Melbourne|North Melbourne|South Melbourne|Richmond|North Richmond"); 
     } 

而在你喜欢这个

01 JavaScript的变化
+0

@Jayanthan:看起来像JsonResult和Json()不支持.net c#webservice – 2011-04-06 03:59:57

1

除了取消注释ScriptService行之外,为什么您的$.ajax()方法以ASPX路径为目标,而您发布的代码来自ASMX服务?这肯定会导致问题。