複数の不要なAJAXリクエストを避けるために、HTMLの隠し要素でJSONを使用します。 JSONは適切に生成されますが、JQueryを使用して処理することはできません。JQueryでHTMLデータ属性をJSONに変換する方法は?
elem.data("json")
は文字列ではなくオブジェクトを返します。parseJSON
は、文字列の先頭に予期しないoがあると言っています。
$(document).ready(function() {
console.log($('#locations-json').data('json'));
console.log(JSON.parse($('#locations-json').data('json'))); # tried parseJSON
$('.class-destination-from').change(function() {
$.when(get_destination_from_state(),function(res){
//if (res=='city'){
//
//}elif(res=='airport'){
// pass
//}elif(res=='empty'){
// pass
//}
});
})
});
これはHTMLの一部である
Object {cities: "[1, 2, 3, 4]", airports: "[5, 6]"} VM1345:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
CONSOLE:
<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div>
は、あなたがそれを正しく変換する方法を知っていますか?
JSONオブジェクトにはクォートキーが必要です: '{" cities ":" [1,2,3,4] "、" airports ":" [5、6] "}' – Frxstrem
[ JSON](http://stackoverflow.com/questions/11338774/serialize-form-data-to-json) – SAM
@TJCrowder質問の最後に要素を追加しました。 –