2017-10-19 25 views
2

私は自分の位置を文字列として表示します。誰かが私にこれを行う方法の手がかりを与えることができますか?私はlaravelとjavascriptにちょうど新しいです。 enter image description hereJSONを文字列に変換JAVASCRIPT

public function myformAjax(Request $request) 
{ 

    $position =Tbl_press_release_recipient::select('position')->where('country',Request::input('country'))->distinct()->get(); 
    return json_encode($position); 
} 

私のAjax:

$(document).ready(function() { 
     $('#country').on('change', function() { 
      var country = this.value; 
      if(country){ 
       $.ajax({ 
        url: '/member/page/press_release_email/choose_recipient_press_release/ajax', 
        type: "GET", 
        data:{country:country}, 
        dataType: "json", 
        success:function(data) { 


         $('select[name="position"]').empty(); 
         $.each(data, function(key, value) { 
          $('select[name="position"]').append('<option value="'+ JSON.stringify(key) +'">'+ JSON.stringify(value) +'</option>'); 

         }); 

        } 
       }); 
      }else{ 
       alert("as23d"); 
      } 
     }); 
    }); 

答えて

1

あなたは値オブジェクトのpositionプロパティにアクセスする必要があるのに対し、あなたは値オブジェクトを文字列化している:

$('select[name="position"]').append(
    $('<option>', { value : value.position, text : value.position }) 
); 

これも作成されますXSSの脆弱性を引き起こす可能性のあるHTMLを連結するのではなく、テキストと値を設定するオプション要素オブジェクトです。あなたのようなJSONを取得AJAX対応している場合

0

{キー:値を}、この点を確認してください。

..., 
success: function(repsonse) { 
    $.each(repsonse, function(i, elem) { 
     $('select[name="position"]').append('<option value="'+ i +'">'+ elem +'</option>'); 
    }); 
} 

jsfiddle:https://jsfiddle.net/tomol1111/7sw53q45/

関連する問題