您好,欢迎访问一九零五行业门户网

怎么用Post方法传递json参数

这次给大家带来怎么用post方法传递json参数,用post方法传递json参数的注意事项有哪些,下面就是实战案例,一起来看一下。
本文主要介绍如何使用angularjs $http服务以post方法向服务器传递json对象数据。
具体如下:
一、$http post方法默认提交数据的类型为application/json
var data = {'wid':'0', 'praise' : '25'};  $http.post(url, data).success(function(result) {   //  });
最终发送的请求是:
post http://www.example.com http/1.1  content-type: application/json;charset=utf-8    {'wid':'0','praise':'25'}
默认的这种方式可以直接将json对象以字符串的形式传递到服务器中,比较适合 restful 的接口。但是php脚本的$_post无法从请求体中获得json数据。
此时可以用:
$data = file_get_contents(php://input); //获得原始输入流
注:enctype=multipart/form-data 的时候 php://input 是无效的
获得请求原始输入流之后再做相应处理就可以获得json数据了。
二、 采用x-www-form-urlencoded 方式提交获得json数据
app.factory(comment,function($http){  return {   get : function(commentfileurl) {    return $http({     method: get,     url: commentfileurl,     params: {r:math.random()},     headers: {'cache-control':'no-cache'}    });   },   //保存一个评论   save : function(tourl,savefileurl,data) {    $http({     method: post,     url: tourl,     data: {saveurl:savefileurl,commit:data},     headers: { 'content-type': 'application/x-www-form-urlencoded' },     transformrequest: function(obj) {      var str = [];      for (var p in obj) {       str.push(encodeuricomponent(p) + = + encodeuricomponent(obj[p]));      }      return str.join(&);     }    }).success(function(data){     console.log(数据已保存!);    }).error(function(data) {     alert(数据保存失败,错误信息: + json.stringify({data:data}));    });   }  } }); var updateclickrate={'wid':'0','click_rate':'87'}; comment.save(php/updatework.php,../userdata/work_content.json,json.stringify(updateclickrate));
最终发送的请求是:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
koa2实现文件上传步奏详解
jquery实现上传图片时预览功能
以上就是怎么用post方法传递json参数的详细内容。
其它类似信息

推荐信息