首頁  >  文章  >  web前端  >  透過建構AJAX參數實現表單元素JSON相互轉換

透過建構AJAX參數實現表單元素JSON相互轉換

亚连
亚连原創
2018-05-24 10:25:541386瀏覽

這篇文章主要介紹了透過建構AJAX參數實現表單元素JSON相互轉換 的相關介紹,需要的朋友可以參考下

ajax提交伺服器數據, 整理一下轉換方法。

HTML:

<form id="fm" name="fm" action="">
<input name="UserName" type="text" value="UserName1"/>
</form>
<input name="UserId" id="UserId" type="text" value="UserId1"/>

#1.表單元素轉QueryString

var q = $(&#39;#fm,#UserId&#39;).serialize(); //q = UserName=UserName1&UserId=UserId1

2.字串,JSON 互相轉換

var obj = jQuery.parseJSON(&#39;{"name":"John"}&#39;);
alert( obj.name === "John" );

可以利用jquery-json外掛實現轉換,直接引用範例

var thing = {plugin: &#39;jquery-json&#39;, version: 2.3};
var encoded = $.toJSON( thing );
// &#39;{"plugin":"jquery-json","version":2.3}&#39;
var name = $.evalJSON( encoded ).plugin;
// "jquery-json"
var version = $.evalJSON(encoded).version;
// 2.3

#3.表單,元素轉Name,Value陣列

var arr = $("#fm,#UserId").serializeArray();
/*[ 
{name: &#39;UserName&#39;, value: &#39;"UserName"1&#39;}, 
{name: &#39;UserId&#39;, value: &#39;UserId&#39;}
] */

#4. 表單元素轉JSON

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || &#39;&#39;);
} else {
o[this.name] = this.value || &#39;&#39;;
}
});
return o;
};
var obj = $(&#39;form&#39;).serializeObject();
/*obj: Object
UserId: "UserId1"
UserName: "UserName1"
__proto__: Object*/

5. JSON2FORM

$.getJSON(&#39;url_to_file&#39;, function(data) {
for (var i in data) {
$(&#39;input[name="&#39;+i+&#39;"]&#39;).val(data[i]);
}
}
data = {
"Name":"Emkay Entertainments",
"Address":"Nobel House, Regent Centre",
"Contact":"Phone"
} 
$(&#39;p#data&#39;).loadJSON(data);
<p id="data">
<h1 id="Name">Emkay Entertainments</h1>
<label for="Address">Address:</label>
<span id="Address">Nobel House, Regent Centre</span> 
<label for="Contact">Contact by:</label>
<span id="Contact">Phone</span>
</p>

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

Boa伺服器下的ajax與cgi通訊(圖文教學)

Ajax Struts2實作驗證碼驗證功能(圖文教學)

Ajax點選不斷載入資料清單(圖文教學)

以上是透過建構AJAX參數實現表單元素JSON相互轉換的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn