码迷,mamicode.com
首页 > Web开发 > 详细

fetch获取json的正确姿势

时间:2017-08-29 11:05:15      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:headers   urlencode   accept   row   text   参数   fun   style   ret   

fetch要求参数传递,遇到请求无法正常获取数据,网上其他很多版本类似这样:

    fetch(url ,{
        method: ‘POST‘,
        headers:{
                    ‘Accept‘: ‘application/json, text/plain, */*‘,
                    ‘Content-Type‘: ‘application/json‘
        },
         body: JSON.stringify({a:1,b:2})
    }).then(function(response){
        return response.json();
    }).then(function(data){
         console.log(data);
    });

经过改进和测试,如下:

var ur = ‘xxx‘,params = {page:1,rows:10},param=‘‘;
for(var key in params){
  param += key + ‘=‘ + params[key] + ‘&‘;
}
if(param) param = param.substring(0,param.length-1);
var requestConfig = {
  method: ‘POST‘,
  credentials: ‘include‘,
  headers: {
    ‘Accept‘:‘application/json, text/plain, */*‘,
    ‘Content-Type‘: ‘application/x-www-form-urlencoded‘               
  }      
};
Object.defineProperty(requestConfig,‘body‘,{
    value: param
});
fetch(url,requestConfig).then(function(res){
   return res.json(); 
}).then(function(json){
   console.log(json.data);
});

 

fetch获取json的正确姿势

标签:headers   urlencode   accept   row   text   参数   fun   style   ret   

原文地址:http://www.cnblogs.com/xtreme/p/7447059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!