我希望使用 ajax 响应返回的值来“选择”选择选项。
数组
$array=array("Price 1","Price 2","Price 3","Price 4","Price 5");
我能想到的就是循环,直到选项与给定值匹配。
echo "<select id='option'>";
foreach($array as $key=>$val){
if(data.option==$key){$selected="selected";}//compare with json from ajax
echo "<option value='$key' $selected>$val</option>"
}
echo "</select>";
我有一个来自ajax的json响应
data.option
= 1。那么,有没有办法实现这个或替代方法呢?
这就是你想要的(在里面做
ajax success
):-
success: function (data) {
$("#option").val(data.option);//this is what you want
}
演示示例:-
$(document).ready(function(){
$("#option").val(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='option'>
<option value="0" selected>Price 1</option>
<option value="1">Price 2</option>
<option value="2">Price 3</option>
<option value="3">Price 4</option>
<option value="4">Price 5</option>
</select>
$(document).ready(function(){
$("#option").val(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='option'>
<option value="0" selected>Price 1</option>
<option value="1">Price 2</option>
<option value="2">Price 3</option>
<option value="3">Price 4</option>
<option value="4">Price 5</option>
</select>
$(document).ready(function(){
$("#option").val(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='option'>
<option value="0" selected>Price 1</option>
<option value="1">Price 2</option>
<option value="2">Price 3</option>
<option value="3">Price 4</option>
<option value="4">Price 5</option>
</select>