2011-04-04 54 views
0

我正在尝试使用jQuery调用Web服务。出于某种原因,结果以XML的形式返回......除了自己编写解析器之外,还有一种更好的方式来获得结果。如何解析或访问从jQuery的Web服务调用返回的值?

这是返回的值:

<?xml version="1.0" encoding="utf-8"?>\r\n<string xmlns="http://tempuri.org/">"Hello World"</string> 

这是HTML:

<script type="text/javascript"> 

    var url = '<%=ResolveUrl("~/Services/ProjectDialog.asmx/HelloWorld")%>'; 

    function callWebService() { 

     jQuery.ajax({ 
      cache: false, 
      type: 'POST', 
      complete: onComplete, 
      data: null, 
      dataType: 'application/json; charset=utf-8', 
      error: onError, 
      success: onSuccess, 
      url: url 
     }); 
    } 

    function onComplete(status, xmlHttpRequest) { 
     var stop = ""; 
    } 
    function onError(xmlHttpRequest, status, error) { 
     var stop = ""; 
    } 
    function onSuccess(data, status, xmlHttpRequest) { 
     var stop = ""; 
    } 

    jQuery(document).ready(function() { 
    }); 

</script> 

<input type="button" value="Run Web Service" onclick="callWebService();" /> 

这是Web服务:

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

namespace My.Services 
{ 
    /// <summary> 
    /// Summary description for ProjectDialog 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    [System.Web.Script.Services.ScriptService] 
    public class ProjectDialog : System.Web.Services.WebService 
    { 
     [WebMethod] 
     public string HelloWorld() 
     { 
      return "Hello World"; 
     } 
    } 
} 
+0

看到我的更新。如果你指定'contentType',你将得到一个有效的'json'响应。 – 2011-04-04 15:12:24

回答

0

我能想到的三个选项,这将是有帮助在这种情况下 -

  1. 包括对Web服务的方法此属性(返回为JSON而不是XML) -

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

  2. Parse the XML在客户端

  3. 或者使用IHttpHandler而不是Web服务。它们很简单,使用起来也很简单。

0

您需要的ScriptMethodAttribute适用于Web服务,并指定ResponseFormat(JSON是默认值)

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string HelloWorld() 
{ 
    return "Hello World"; 
} 

这很可能会是你最好的结果,因为它似乎要请求的数据作为JSON反正基于您的.ajax()电话。 注意基于jQuery docs,数据类型应简单地为json

通过使用dataType选项可以实现不同的数据处理 。 除了纯XML,数据类型可以是 html,json,jsonp,脚本或文本。

更新 如果指定contentType正确,你会得到一个有效的json反应看来。

jQuery.ajax({ 
    cache: false, 
    type: 'POST', 
    complete: onComplete, 
    data: null, 
    contentType: "application/json; charset=utf-8", 
    dataType: 'json', 
    error: onError, 
    success: onSuccess, 
    url: url 
});