2017-10-19 199 views
2

我希望我的位置顯示爲一個字符串。有人可以告訴我如何做到這一點?我只是新的laravel和JavaScript。 enter image description here將JSON轉換爲字符串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

你字符串化的值對象,而您需要訪問值對象的位置屬性:

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

這也創造了一個選項元素對象來設置文本和值,而不是連接可能導致XSS漏洞的HTML。

0

如果Ajax響應你的JSON像{鍵:值},看看這個:

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

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