Ajax Step By Step5

來源:互聯網
上載者:User

標籤:指定   處理   初始化   單選   單選框   提交   多次   jquery   jquer   

第五.【表單序列化】

Ajax 用的最多的地方莫過於表單操作,而傳統的表單操作是通過 submit 提交將資料傳 輸到伺服器端。如果使用 Ajax 非同步處理的話,我們需要將每個表單元素逐個擷取才方能提 交。這樣工作效率就大大降低.

對比資料轉送的差別:

//常規形式的表單提交$(‘form input[type=button]‘).click(function(){ $.ajax({ type:‘POST‘, url:‘test.php‘, data:{user:$(‘forminput[name=user]‘).val(), email:$(‘form input[name=email]‘).val() }, success:function(response,status,xhr){ alert(response); } }); });

注意:當資料很多時user 和email位置擷取資料容易出錯。

怎麼解決該問題呢??

方法為:使用表單序列化方法.serialize(),會智能的擷取指定表單內的所有元素。這樣,在面對大量表單元素時,會把表單元素內容序列化為字串,然後再使用 Ajax 請求。

(2) //使用.serialize()序列化表單內容$(‘forminput[type=button]‘).click(function(){ $.ajax({ type:‘POST‘, url:‘test.php‘, data:$(‘form‘).serialize(), success:function(response,status,xhr){ alert(response); } })});

特別注意:.serialize()方法不但可以序列化表單內的元素,還可以直接擷取單選框、複選框和下拉 列表框等內容。

(2.1)//使用序列化得到選中的元素內容

$(‘:radio‘).click(function(){ $(‘#box‘).html(decodeURIComponent($(this).serialize())); // decodeURIComponent編碼轉換});

知識點:返回 JSON 資料的方法:.serializeArray()。這個方法 可以直接把資料整合成索引值對的 JSON 對象。

$(‘:radio‘).click(function(){ console.log($(this).serializeArray()); var json=$(this).serializeArray(); $(‘#box‘).html(json[0].value); })

有時,我們可能會在同一個程式中多次調用$.ajax()方法。而它們很多參數都相同,這個時候我們可以使用 jQuery 提供的$.ajaxSetup()請求預設值來初始化參數。

$(‘forminput[type=button]‘).click(function(){ $.ajaxSetup({ type:‘POST‘, url:‘test.php‘, data:$(‘form‘).serialize() }); $.ajax({ success:function(response,status,xhr){ alert(response); } }); });

在使用 data 屬性傳遞的時候,如果是以對象形式傳遞索引值對,可以使用$.param()方法 將對象轉換為字串索引值對格式。

Var obj={a:1,b:2,c:3}; var  form=$.param(obj);  //將obj json對象轉成字串索引值對alert(form);

 

Ajax Step By Step5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.