[英]Convert JSON to string JAVASCRIPT
我希望我的位置顯示為字符串。 有人可以告訴我如何做到這一點嗎? 我剛接觸 laravel 和 javascript。
public function myformAjax(Request $request)
{
$position =Tbl_press_release_recipient::select('position')->where('country',Request::input('country'))->distinct()->get();
return json_encode($position);
}
我的阿賈克斯:
$(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");
}
});
});
您正在對值對象進行字符串化,而您需要訪問值對象的位置屬性:
$('select[name="position"]').append(
$('<option>', { value : value.position, text : value.position })
);
這還會創建一個選項元素對象來設置文本和值,而不是連接可能導致 XSS 漏洞的 HTML。
如果在 ajax 響應中你得到類似 {key: value} 的 json,請檢查:
...,
success: function(repsonse) {
$.each(repsonse, function(i, elem) {
$('select[name="position"]').append('<option value="'+ i +'">'+ elem +'</option>');
});
}
jsfiddle: https ://jsfiddle.net/tomol1111/7sw53q45/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.