Jquery通過JSON字串建立JSON對象,jqueryjson
<html><body><h2>通過 JSON 字串來建立對象</h3><p>First Name: <span id="fname"></span><br /> Last Name: <span id="lname"></span><br /> </p> <script type="text/javascript">//txt為字串var txt = '{"employees":[' +'{"firstName":"Bill","lastName":"Gates" },' +'{"firstName":"George","lastName":"Bush" },' +'{"firstName":"Thomas","lastName":"Carter" }]}';//通過eval()方法//var obj = eval ("(" + txt + ")"); //通過JSON解析//obj = jQuery.parseJSON(txt);obj = JSON.parse(txt);document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script></body></html>
jquery中json對象轉為一般字元串
serialize()傳回值是字串。
serializeArray()此方法返回的是JSON對象而非JSON字串。需要使用外掛程式或者第三方庫進行字串化操作。
jquery1.4API中有個例子是這麼把JSON對象轉成字串的。
樣本
描述:
取得表單內容並插入到網頁中。
HTML 程式碼:
<p id="results"><b>Results:</b> </p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>
jQuery 代碼:
var fields = $("select, :radio").serializeArray();
jQuery.each( fields, function(i, field){
$("#results").append(field.value + " ");
});...餘下全文>>
Jquery怎將一個object對象轉換成json字串?
");??}??});啟動並執行結果每次都是:失敗,請稍後再試!沒有跳轉到背景函數。
我調試了,就是 jQuery.toJSON(obj) 的問題,去掉它就可以調到背景函數裡。
發送到伺服器的資料。將自動轉換為請求字串格式。GET 請求中將附加在 URL 後。查看 processData 選項說明以禁止此自動轉換。必須為"{鍵:值}"格式。如果為數組,jQuery 將自動為不同值對應同一個名稱。如 {foo:["bar1", "bar2"]} 轉換為 '&foo=bar1&foo=bar2'。 如果值是一個數組( Array ), jQuery將在 多個連續的值具有相同的索引值的基礎上建立的傳統設定
這裡不需要轉化啊,把你的代碼改成
data:obj,試試