无法使用钛从WCF数据服务中读取数据

时间:2014-01-15 09:52:55

标签: titanium

我创建了一个返回JSON格式的WCF数据服务

public static void InitializeService(DataServiceConfiguration config)         {             // TODO:设置规则以指示哪些实体集和服务操作是可见的,可更新的等。             // 例子:             config.SetEntitySetAccessRule(“”,EntitySetRights.AllRead);             config.SetServiceOperationAccessRule(“”,ServiceOperationRights.All);             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;         }

我用钛连接到网络服务来获取数据

var label = Titanium.UI.createLabel({         顶:300     });

var data = [];

// Connecting to WCF data service 
var xhr = Titanium.Network.createHTTPClient();
var theURL = 'http://localhost:4338/DataService.svc/Orders?$format=json';
var json;
xhr.onload = function (){
    var json = JSON.parse(this.responseText); 
};

for (var i = 0 ; i < json.length; i++)
{
    data.push(json[i]);
}
label.text = data[0].OrderID;
xhr.open('Get',theURL);

出了什么问题

1 个答案:

答案 0 :(得分:1)

首先,您必须知道HTTP请求是异步,这意味着虽然获取响应需要一些时间(取决于Internet连接,服务器速度,数据大小等)。 ),执行后续代码。如果请求是同步的,它会在加载时阻止应用程序和任何用户交互。这就是客户端提供针对某些状态更改触发的回调的原因。

您的代码

var data = [];

// Connecting to WCF data service 
var xhr = Titanium.Network.createHTTPClient();

// Just guessing, but is the $ necessary?
var theURL = 'http://localhost:4338/DataService.svc/Orders?$format=json';

// You are defining json here 'globally'
var json;

xhr.onload = function (){

    // You are defining the json variable within the scope of
    // the onload function, so it can't be accessed from outside
    // the function. Moreover, you are overwriting json of the global scope
    // within this function
    var json = JSON.parse(this.responseText);

};

// At this point, json is undefined
// Moreover, this code is executed before xhr.onload fires
for (var i = 0 ; i < json.length; i++)
{
    data.push(json[i]);
}
label.text = data[0].OrderID;
// Method should be GET not Get
xhr.open('Get',theURL);


如何运作

var data = [];
var theURL = 'http://localhost:4338/DataService.svc/Orders?format=json';
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function (){
    // Assuming that you have a valid json response
    var json = JSON.parse(this.responseText);
    for (var i=0; i < json.length; i++) {
        data.push(json[i]);
    }
    // For testing, otherwise make sure it won't break if your response is empty
    label.text = data[0].OrderID;
};
xhr.open('GET', theURL);