jquery和angular的ajax請求的區別

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

最近用angular替換我blog的部分頁面。結果悲劇的發現,post請求到revel以後,revel的ParamsFilter解析不粗來參數。

看了下請求資訊,發現jquery和angular的post請求是有些不同的。

jquery的content type是application/x-www-form-urlencoded,會把post的參數拼接到url上,格式如foo=bar&baz=moe這樣的。

而angular裡,預設content type 是application/json,資料是以json格式發過去的。

但是在revel的params.go裡面,沒有對json格式的請求做參數處理。

用作者的原話說,這個json的處理沒有什麼用,而且在controller裡用encoding/json處理也只是幾行代碼的事情。所以,就沒有所以了。。。

關於這個問題的解決方案,有很多,可以從angular層面解決,把angular的post請求也按照jquery的方法做些改變,如下:

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

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

也可以從revel服務端解決。

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"} )

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.