我正在使用 PhoneGap 和 jQuery Mobile 开发移动应用程序。我的目标是创建一个 Web 服务,使客户端(移动设备)能够查询数据库。
经过一番研究,我发现 AJAX Enabled Services 可能正是我所寻找的。 因此,我首先创建一个支持 AJAX 的 WCF 服务,现在我仅添加了以下方法:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]
public string GetString()
{
return "Hello there";
}
我的 web.config 如下所示:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication1.MobileServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication1.MobileService">
<endpoint address="" behaviorConfiguration="WebApplication1.MobileServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication1.MobileService" />
</service>
</services>
</system.serviceModel>
</configuration>
完成此服务后,我使用以下方法从客户端调用:
$.ajax({
type: "POST",
url: "http://localhost:11634/MobileService.svc/GetString",
contentType: "application/json",
data: "{}",
dataType: "json",
success: function (result) {
$("#textbox").text(result);
},
error: function (textStatus) {
alert(textStatus);
}
});
调用服务时,我收到以下错误[object Object]
。您能否指导我做错了什么以及我是否使用了正确的技术?
最佳答案
正如 Tariqulazam 正确指出的那样,[Object object] 不是错误,而是响应对象。要访问数据,您可以修改代码以读取:
success: function (result) {
var data = result.d
$("#textbox").text(data);
},
如果您想查看教科书示例,下面看起来像是使用 WCF Web 服务的 jQuery 代码的一个很好的示例:
Consuming WCF service using jQuery
希望这有帮助!
关于wcf - 从 jQuery 调用启用 AJAX 的 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12905189/