2011-10-10 113 views
0

我从不是项目一部分的jQuery文件调用.NET Web服务。每当我打电话给服务时,它说OPTIONS /HOCWebService.asmx/HelloWorld并且不返回任何东西。到底是怎么回事?在web.config中,我已经指定Web服务允许httpGet和httpPost。从jQuery调用.NET Web服务

更新1:

$.ajax(

    { 
     type: "POST", 
     url: "http://127.0.0.1:8080/HOCWebService.asmx/HelloWorld", 
     data: "{}", 
     dataType: "json", 
     contentType: "application/json", 
     success: function (response) { 

      alert(response.d); 

      var categories = $.evalJSON(response.d); 


      for (i = 0; i < categories.length; i++) { 

       var span = $(document.createElement("span")); 
       $(span).addClass("ui-li-count"); 
       $(span).html(categories[i].Count); 
       var li = $(document.createElement("li")); 
       var anchor = $(document.createElement("a")); 
       $(anchor).attr("href", "/Home/detail/"+categories[i].Id); 
       $(anchor).html(categories[i].Title); 

       $(li).append(anchor); 
       $(li).append(span); 

       //  $("#categoriesListView").append('<li><a href="/Home/detail/' + categories[i].Id + '">' + categories[i].Title + '</a></li>'); 

       $("#categoriesListView").append(li); 

       // $(span).text(categories[i].Count); 

      } 

      $("#categoriesListView").listview('refresh'); 

     } 
    } 

    ); 
+0

你可以为$ .ajax()调用添加代码吗? –

+0

@StevendeSalas代码已添加! – azamsharp

回答

2

的ASMX文件在.NET框架的默认实现意味着你正在处理SOAP Web服务,因此将被发送和接收XML wrapped in a SOAP envelope(而不是JSON)。

尝试:

$.ajax({ 
      // 1. Loose the 'HelloWorld' from the URL 
      url: "http://127.0.0.1:8080/HOCWebService.asmx", 
      type: 'POST', 
      async: false, 
      dataType: 'xml', 
      // 2. But add it as a HTTP Header called 'SOAPAction' 
      headers: { 
      SOAPAction: "http://www.tempuri.org/HelloWorld" 
      }, 
      contentType: 'text/xml; charset="utf-8"', 
      // 3. The data sent to the server must be a SOAP XML Envelope 
      data: '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
        '<soap:Body>' + 
         '<HelloWorld xmlns="http://www.tempuri.org/" />' + 
        '</soap:Body>' + 
       '</soap:Envelope>', 
      sucess: function(response) { 
       alert(response.responseText); 
       // Completion logic goes here 
      } 
    }); 

请注意,作为执行工作的一部分上面你需要一个HTTP POST头被称为“SOAPAction的”匹配您所呼叫的方法,否则它不会工作:

headers: { 
    SOAPAction: "http://www.tempuri.org/HelloWorld" 
}, 

表示POST请求将包括以下最后一行:

POST /HOCWebService.asmx HTTP/1.1 
Host: 127.0.0.1:8080 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: 453 
SOAPAction: "http://www.tempuri.org/HelloWorld" 

http://www.tempuri.org/是Microsoft在创建新的ASMX服务时使用的默认命名空间,随时将其更新为您在实现中使用的实际命名空间。

建议:

如果你需要从你的应用程序来回发送JSON,使用something similar to this approach我可以建议你使用一个通用的处理程序(ASHX文件)。