1

我有一个具有以下结构的 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>");
           }


       }
   })
4

1 回答 1

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);
于 2013-04-27T20:45:56.817 回答