1.5 ionic入門——http get post

(1)app.module.ts中引入javascript

import { HttpModule,JsonpModule} from '@angular/http'; 

(2)在imports中注入 HttpModule和JsonpModulejava

imports: [

    BrowserModule,

    HttpModule,

    JsonpModule,

    IonicModule.forRoot(MyApp)

  ],

(3)在須要的頁面中引入json

import { Http,Jsonp,Headers} from '@angular/http'; 

(4)構造函數中聲明app

constructor(public navCtrl: NavController, public navParams: NavParams,private http:Http,private jsonp:Jsonp) { } 

(5)get請求函數

this.http.get(your_url).subscribe( function(res){ var mydata = res.json(); },function(err){ var errdata = err.json(); console.log("信息:"+errdata.message); }); 

(6)post請求post

1.設置頭文件jsonp

private headers = new Headers({'Content-Type':'application/json'}); 
2.上傳參數 var params = { schoolId:"2015202050006", grade:"2015", name:"張三", password:"123456", role:"學生", telphone:"13888888888" }; 3.上傳 this.http.post(url,JSON.stringify(params),{headers:this.headers}).subscribe(function(res){ console.log(res); var mydata = res.json(); console.log("註冊成功"); },function(err){ console.log("sorry,註冊失敗"); var data = err.json(); console.log(data); alert("註冊失敗",data.message); //返回前一頁 }); 

(7) post數據爲formData
不要設置頭文件,否則報錯,頭文件空着ui

private headers = new Headers(); 
相關文章
相關標籤/搜索