【发布时间】:2014-08-15 00:14:04
【问题描述】:
我有一个托管在 IIS 中的 WCF 服务,并在通过浏览器调用时正确返回 JSON 数据。
我正在尝试通过 Jquery Ajax 调用来使用该服务。 WCF 和 Jquery 应用程序都在同一个域中。
我检查了 cmets 是否有类似的问题:
Consuming a WCF Service in jQuery via AJAX Call in a different Project (Cross Domain),不幸的是我可以从上面解决我的问题。
我的 WCF 服务 Web.config
<system.serviceModel>
<services>
<service name="MyWCFService.Service1" behaviorConfiguration="MyWCFService.Service1Behavior">
<endpoint address="Service1"
binding="basicHttpBinding"
contract="MyWCFService.IService1"/>
<endpoint address="../Service1.svc"
binding="webHttpBinding"
contract="MyWCFService.IService1"
behaviorConfiguration="webBehaviour" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWCFService.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
方法签名:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
List<Employee> GetEmployeeIDs(String value);
员工等级:
[DataContract]
public class Employee
{
[DataMember]
public string ID { get; set; }
}
当我从浏览器点击以下 URL 时返回的数据
URL : http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984
Result from Browser :
{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"},{"ID":"239845"},{"ID":"239846"},{"ID":"239847"},{"ID":"239848"},{"ID":"239849"}]}
jQuery 调用:
function Call_WCF_JSON() {
var result = ""
var ArgValue = '23984';
$.getJSON("http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984", {},
function(data) {
alert(data);
console.log(data);
});
//GetEmployeeIDs is a function which has Value as String Argument
$.ajax({
type: "GET",
url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs",
async: false,
data: '{"value":"' + ArgValue + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var oObj;
oObj = jQuery.parseJSON(data);
alert(oObj);
console.log(oObj);
var oRealObj;
oRealObj = jQuery.parseJSON(oObj.GetEmployeeIDsResult);
alert(oRealObj);
console.log(oRealObj);
},
failure: function (response) {
alert(response);
console.log(response);
}
});
}
编辑 1:使用以下代码重新创建整个应用程序
带有单个 JSON 绑定的 Webconfig 文件
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="Emp_JSON_Srvc.Service1" behaviorConfiguration="Emp_JSON_Srvc.Service1Behavior">
<endpoint address="../Service1.svc"
binding="webHttpBinding"
contract="Emp_JSON_Srvc.IService1"
behaviorConfiguration="webBehaviour" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Emp_JSON_Srvc.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
接口代码:
namespace Emp_JSON_Srvc
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
List<Employee> GetEmployeeIDs(String value);
}
[DataContract]
public class Employee
{
[DataMember]
public string ID { get; set; }
}
}
服务类
namespace Emp_JSON_Srvc
{
public class Service1 : IService1
{
public List<Employee> GetEmployeeIDs(String value)
{
List<Employee> results = new List<Employee>();
results.Add(new Employee() { ID = "239840" });
results.Add(new Employee() { ID = "239841" });
results.Add(new Employee() { ID = "239842" });
results.Add(new Employee() { ID = "239843" });
results.Add(new Employee() { ID = "239844" });
return results;
}
}
}
我在浏览器中输入 URL 时的结果
URL : http://localhost:60529/Service1.svc/GetEmployeeIDs/98
(I have fixed the port number in Visual Studio. hence it wont change for each run)
{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"}]}
Javascript 使用 Json
function Call_WCF_JSON() {
var result = ""
alert('Method 1 : Start');
$.getJSON("http://localhost:60529/Service1.svc/GetEmployeeIDs/98", {},
function (data) {
alert(data);
console.log(data);
});
alert('Method 2 : Start');
var query = { sValue: '98' };
$.ajax({
type: "POST",
url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Method 2 : Success");
/*
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
*/
},
error: function (e) {
alert('Method 2 : Error');
alert('Method 2 : --> ' + e.responseText);
}
});
alert('Method 3 : Start');
var value = '98'
$.ajax({
type: "GET",
url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
cache: false,
data: JSON.stringify(value),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert("Method 3 : Success");
alert(JSON.stringify(msg));
},
error: function (err) {
alert('Method 3 : Error');
}
})
alert('Method 4 : Start');
var ArgValue = '98';
$.ajax({
type: "GET",
url: "http://localhost:60529/Service1.svc/GetEmployeeIDs",
async: false,
data: '{"value":"' + ArgValue + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Method 4 : Success");
var oObj;
oObj = jQuery.parseJSON(data);
alert(oObj);
console.log(data);
var oRealObj;
oRealObj = jQuery.parseJSON(oObj.GetHostServersResult);
alert(oRealObj);
console.log(oRealObj);
//alert(data.GetHostServersResult[0].Name);
},
failure: function (response) {
alert('Method 4 : Error');
alert(response);
}
});
}
我从 javascript 得到的结果是
Method 1 : Start
Method 2 : Start
Method 2 : Error
Method 2 : --> undefined
Method 3 : Start
Method 3 : Error
Method 4 : Start
欢迎提出任何建议。
谢谢!!
【问题讨论】:
-
你为什么要做
alert(data.d);?在您的示例 JSON 响应中没有元素d... -
我对以前的 JSON 数据使用了相同的 Jquery 代码,当我返回一个字符串值时它就起作用了。刚刚尝试了警报(数据);它只是给了我空白警报弹出窗口。将我的帖子编辑为警报(数据);而不是 alert(data.d);
-
是的,但它会返回 JSON。因为您定义了
dataType: "json",所以它已经是一个javascript 对象。要在警报中显示某些内容,它需要如下所示:alert(data.GetEmployeeIDsResult[0].ID);。也尝试通过在失败函数中添加警报来检查是否有失败。 -
刚刚尝试将代码编辑为 :-- 成功:function (data) { result = data.GetEmployeeIDsResult[0].ID;警报(结果); },失败:函数(响应){警报(响应); } 似乎没有回应伙伴。有没有办法检查 javascript 代码是否实际上在数据对象中保存了任何数据?谢谢!!
-
我真诚的道歉队友,在 ajax 调用显示结果变量后有一个警报。已显示为空白弹出窗口。对困惑感到抱歉。我想我无法从服务器获取任何数据/可能是我没有正确处理数据。但我确信服务在浏览器上测试时会提供数据