獲取form表單的值並轉化為字串、JSONArray或JSONObject的方法及form取不到值的解決辦法
阿新 • • 發佈:2019-01-07
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">form表單提交時,可能需要轉化為不同的形式來作為引數請求介面。本文總結了將form表單的值並轉化為字串、JSONArray或JSONObject的方法。</span>
1. form轉化為字串
<pre name="code" class="html"><pre name="code" class="html">var a=$('form').serialize(); alert(a);
該方法將form值轉化為 key=value&key=value 的形式。
2. form轉化為JSONArray
var a=$('form').serializeArray();
var str=JSON.stringify(a);
alert(str);
3. form轉化為JSONObject
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="html"><span style="white-space:pre"> </span>function submit(){ var a=$('form').serializeObject() ; var str=JSON.stringify(a); console.info(str); } $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [ o[this.name] ]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }
附:form表單取不到input textarea值的解決辦法
以上方法均可獲取到input textarea的值,如果alert為空字串,請檢查input textarea的name屬性是否已賦值,如沒有name屬性,則form取不到該文字框的值。