从Phonegap调用ASP.NET Web Service

3

你好,我一直在尝试从 PhoneGap Android 应用程序中调用一个使用 ASP.NET 编写的 Web 服务,但似乎出了一些错误。

值得一提的是,当我在 Eclipse 的 Android 模拟器上运行它时会失败。我已经在 Web 浏览器中尝试了相同的代码,它可以正常工作。

这里是与问题相关的 Index.html 部分

/* Here i declare 'webServiceURL' which holds the path to the service that's
   hosted at 10.0.0.174 (WLAN ip of my computer). I use this instead of 127.0.0.1
   because on a mobile phone localhost points to the phone itself. */

// Here i declare 'datos' which are the parameters sent to the web service method 

$.ajax({
  url: webServiceURL + "InicioSesion",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify(datos),                    
  dataType: 'json',
  beforeSend: function() {$.mobile.loading('show')},
  complete: function() {$.mobile.loading('hide')},
  success: function (data, textStatus, jqXHR) {
    // Here i do stuff with 'data'
  },
  error: function (jqXHR, textStatus, errorThrown) {
    // Here i print errors
  },
)};

在phonegap的config.xml中添加了Access origin权限

<access origin="*"/>

修改 ASP.NET Web 服务的 web.config

<system.webServer>
  <httpProtocol>
   <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
   </customHeaders>
  </httpProtocol>
</system.webServer>

我遇到的错误是,当我将 'dataType' 设置为 'json'(这就是我期望的)时,ajax 请求失败,并且打印 'textStatus' 返回“ParserERROR”。
因此,我尝试使用 'dataType' 作为 'text' 而不是 'json',以查看 Web 服务响应是否有问题,并且我意识到问题是响应为空。
请注意,这段代码在 Web 浏览器上运行得非常完美,但在运行从 Android 模拟器中运行的 PhoneGap 应用程序时会失败。
如果有任何使用 PhoneGap 消耗 ASP.NET Web 服务经验的人能帮帮我!我不知道我错过了什么或做错了什么!我已经在处理这个问题已经2天了,但我就是找不到解决办法!
2个回答

3

我已经找到了我犯的错误!

在添加到Phonegap config.xml 的访问来源权限中,我一直在输入:

<access origin="*"/>

那是不正确的!正确的方法是在星号('*')前加一个点('.'):

<access origin=".*"/>

就是这样,问题解决了!.


1
你可能需要使用[System.Web.Script.Services.ScriptService]修饰你的Web服务,以便让它可以被JavaScript客户端调用。 示例:
[WebService(Namespace = "http://tempuri.org/&quot;)]  
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
[System.Web.Script.Services.ScriptService]  
public class dummyWebservice : System.Web.Services.WebService  
{  
[WebMethod()]  
public string HelloToYou(string name)  
{  
return "Hello " + name;  
}  
[WebMethod()]  
public string sayHello()  
{  
return "hello ";  
}    
} 

来源和其他信息 / 示例:http://vincenthomedev.wordpress.com/2009/02/10/consuming-an-aspnet-web-service-or-page-method-using-jquery/


是的,我的 Web 服务包括 [System.Web.Script.Services.ScriptService],无论如何还是谢谢!。 - Luis Crespo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接