我有一个localStorage,它具有以下结构:
[{"id" : "1", "n" : "Ferrari testarrosa"},{"id" : "2", "n" : "Honda prelude"}......]
我需要填写此localStorage中的选项和选项,以获取:
<option value='1'>Ferrari testarrosa</option>
PHP
<? require('pr13conecta.php');
$cadena="";
ini_set('display_errors',1); error_reporting(E_ALL);
$cSQL="SELECT ID, CADENA FROM MASIVO;";
$stmt=$oConni->prepare($cSQL) or die($oConni->error);
$stmt->execute();
$stmt->bind_result($id, $texto);
while ($stmt->fetch()) {
$cadena.='{"id" : "'.$id.'", "n" : "'.$texto.'"},';
}
$stmt->close();
echo $cadena;
JAVASCRIPT
$.ajax({type: "POST",
url: "pr13llenaSelect.php",
success:function(data) {
localStorage.setItem('selids','['+data+']');
for (x=0; x<=localStorage.length-1; x++) {
$('#selCadena').html("<option value="'+localStorage.getItem('selids')+'">"+localStorage.getItem('selids')+"</option>");
}
}
})
答案 0 :(得分:1)
这应该让它运作
JAVASCRIPT
$.ajax({
type: "POST",
url: "pr13llenaSelect.php",
dataType : "json",
success:function(data) {
localStorage.setItem('selids',JSON.stringify(data));
$("#selCadena").empty();
$.each(JSON.parse(localStorage.selids),function(){
var thisItem = this;
$("#selCadena").append(
$("<option>").attr("value",thisItem.id).html(thisItem.n)
);
});
}
});
还建议在php代码中使用json_encode
PHP
<? require('pr13conecta.php');
$cadena=array();
ini_set('display_errors',1); error_reporting(E_ALL);
$cSQL="SELECT ID, CADENA FROM MASIVO;";
$stmt=$oConni->prepare($cSQL) or die($oConni->error);
$stmt->execute();
$stmt->bind_result($id, $texto);
while ($stmt->fetch()) {
array_push($cadena,array("id" => $id, "n" => $texto);
}
$stmt->close();
echo json_encode($cadena);