2016-09-30 32 views
1

複数の不要な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="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 

は、あなたがそれを正しく変換する方法を知っていますか?

+1

JSONオブジェクトにはクォートキーが必要です: '{" cities ":" [1,2,3,4] "、" airports ":" [5、6] "}' – Frxstrem

+0

[ JSON](http://stackoverflow.com/questions/11338774/serialize-form-data-to-json) – SAM

+0

@TJCrowder質問の最後に要素を追加しました。 –

答えて

3

問題は、たいていの場合、dataはほとんどの人がそれとは思わないということです。 dataではなく、アクセサーのdata-*プロパティでは、それは多かれ少なかれです。これは、要素のjQueryの内部データキャッシュを管理します。 は、data-*属性からキャッシュされたを初期化しますが、キャッシュ内のデータを複製し、データを処理し、決して属性に書き戻しません。

dataは、あなたが読んでいるものがJSONであることを自動的に検出し、として解析します。だから、オブジェクトを取り戻し、それを解析する必要はありません。

のでdata使用して:あなたは12個の都市があると言うコメントで述べたように

var locations = $("#locations-json").data("json"); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

を。

{"cities": [1, 2, 3, 4], "airports": [5, 6]} 

例:

var locations = $("#locations-json").data("json"); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: [1, 2, 3, 4], &quot;airports&quot;: [5, 6]}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

おそらくあることをJSONを意味

{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"} 

:JSONはcities(およびairports文字列値与えているためです あなたがdataのさまざまな機能を必要としない限り、


しかし、自分だけをattrを使用して解析:

var locations = JSON.parse($("#locations-json").attr("data-json")); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: [1, 2, 3, 4], &quot;airports&quot;: [5, 6]}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


注:

としてthis editの、あなたの質問このように見える有効なdivがありました:

<div id="locations-json" data-json="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 

しかし、その後you edited it againが無効である、このように見えるように:&quot;

<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div> 

バージョンが正しいか、それを使用してください。

+0

JSONを正しく解析するかどうかはわかりませんが、私はこのエリアで新しくなっているので正しいかもしれません。私がするとき:$( '#locations-json')。data( 'json')都市それは正しい[1,2,3,4]を返します。しかし、私が最初の都市を取得しようとすると - それは配列が文字列であると思うように "["を返します。 –

+0

@MilanoSlesarik:あなたの要素の 'json'属性が正しく出力されていることを確認する必要があります。私はまた、上記の答えの最後にそれについてのメモを追加しました。 –

+0

多分私は何かを得ることはできませんが、あなたのコードは12の都市があるので、値は配列/リストではなく文字列を考慮して返します。 –

関連する問題