在Titanium中发送一个post httpclient请求

时间:2015-03-04 00:52:37

标签: javascript post titanium appcelerator onload

var xhr=Titanium.Network.createHTTPClient({
    onload:function(e){
    if(this.status == '200'){
          Ti.API.info('got my response, http status code ' + this.status);
           if(this.readyState == 4){
                var response=JSON.parse(this.responseText);
                success = true;
                }
            else{
                alert('HTTP Ready State != 4');
            }           
        }
        else{
            alert('HTTP Error Response Status Code = '+this.status);
            Ti.API.error("Error =>"+this.response);
        }              
    },

});
xhr.onerror = function(e){ 
};

xhr.open("POST","http://localhost:23003/api/user?username=dp&password=123456" ,true);//ADD your URL

xhr.setRequestHeader("content-type", "application/json");

xhr.send();  // Taa da

您好,上面提到的是我的代码,我正在尝试将帖子请求发送到 open 方法中提到的本地服务器进程。但我使用了一些控制台消息来查看返回的对象

  1. this.responseText - 此文本为空白。 (我知道java脚本以不同的方式返回null,并且警报消息显示为&null;'为空。)
  2. this.status - 返回' 0'
  3. this.readyState返回4
  4. var response = JSON.parse();是一个空白文本
  5. 我已尝试将内容类型更改为-application / x-www-form-urlencoded但我得到相同的结果
  6. 我不知道我错在哪里。任何帮助将不胜感激。谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

您的服务器端代码看起来有问题,因为以下内容:

  var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
      console.info(this.status);
      console.info(this.readyState);
      console.info(this.responseText);
    }
  });
  xhr.open("POST", "http://requestb.in/ynwa0gyn");
  xhr.setRequestHeader("content-type", "application/json");
  xhr.send();

正确地给出:

[INFO]  200
[INFO]  4
[INFO]  ok

访问http://requestb.in/ynwa0gyn?inspect以获取客户提出的请求。