jquery和angular的ajax请求的区别

最近用angular替换我blog的部分页面。结果悲剧的发现,post请求到revel之后,revel的ParamsFilter解析不粗来参数。jquery

看了下请求信息,发现jquery和angular的post请求是有些不一样的。git

jquery的content type是application/x-www-form-urlencoded,会把post的参数拼接到url上,格式如foo=bar&baz=moe这样的。angularjs

而angular里,默认content type 是application/json,数据是以json格式发过去的。github

可是在revel的params.go里面,没有对json格式的请求作参数处理。ajax

用做者的原话说,这个json的处理没有什么用,并且在controller里用encoding/json处理也只是几行代码的事情。因此,就没有因此了。。。json

关于这个问题的解决方法,有不少,能够从angular层面解决,把angular的post请求也按照jquery的方法作些改变,以下:app

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/post

https://github.com/petersirka/total.js/issues/26url

也能够从revel服务端解决。code

https://github.com/robfig/revel/issues/97

本页的代码修改以下:

func (c *Task) NewTask() revel.Result {

    decoder := json.NewDecoder(c.Request.Body)

    var content ToDoContent

    if err := decoder.Decode(&content); err != nil {

        print(">>>err:", err)

    } else {

        print(">>>>content:", content.Content)

    }

    json.Marshal(content)

    return c.RenderJson(content)

}

虽然这样代码确实很少,不过瞬间感受比rails弱爆了。。。

顺带的提一下,若是是jquery的请求,也须要稍微改动一下的,不然,revel同样的解析不粗来。

在jquery里要把post的jsonstringify一下。

具体参考这里https://github.com/robfig/revel/issues/126

$.ajax({

  type:"POST", 

  url:"/Application/Index", 

  data:JSON.stringify({ name: "John", time: "2pm" }), 

  contentType:"application/json",

  dataType:"json"

} )
相关文章
相关标签/搜索