Pergunta

Aqui está o meu código. Você deve procurar que isso sofra da 'mesma política de origem' nessa forma. O domínio para html é (http://127.0.0.1/jqload.html) & php (http://127.0.0.1/conn_sql.php). Este é o formato JSON: [{"Options": "smart_exp"}, {"options": "user_int"}, {"options": "blahblah"}] eu realmente quero anexar dados JSON que recebo no htyml com usuário Entrada e estou sofrendo nisso. Se eu usar o aval para análise, funciona bem para apontar sua colocação aqui. Mas se eu usar o JSON.PARSE para analisar, todo o código para de funcionar e esta mensagem de erro é emitida '"IMPORTANTE: Remova esta linha do JSON2.JS antes da implantação". Coloquei meu código para outra pergunta no Forum Stackoverflow e me disseram que meu código sofre com a 'mesma política de origem' que causa os problemas na anexação de dados JSON. Então, você pode ver gentilmente meu código sofre com essa política? Embora eu tenha dúvidas que sofre com essa política ao saber que restringe se os arquivos residem em diferentes domínios, aqui os dois arquivos residem um ao lado do outro.

Código:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
 <body> 
  <form name="index">
   <p><input type = "text" id = "txt" name = "txt"></input>
   <p><input type = "button" id = "send" name = "send" value = "send" onClick= 
       "ADDLISTITEM"></input>
   <p><select name="user_spec" id="user_spec" />
  </form>
  <script>
  function ADDLISTITEM()
  {
      alert (json.length); // working
      alert json.options[1]; // do not show any value, message just for testing
      json.options[json.length+1] = 'newOption'; //not working; HELP HERE
      jsonString = JSON.stringify(json);//working fine for current data
      alert(jsonString);
      //here I have to implement send this stringify(json) back to server,HELP  
      //HERE     
  }                    
  </script>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
  var json;
  $(document).ready(function() { 
      jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
          json = jsonData;
          $.each(jsonData, function (i, j) {
              document.index.user_spec.options[i] = new Option(j.options);
          });
      });
  });
  </script>
 </body>
</html>
Foi útil?

Solução

Você está no caminho certo, mas aqui: $.each(jsonData, function (i, j) { ... } você está realmente percorrendo cada personagem do jsonData string, e não o json objeto. Basta mudar de jsondata para json dentro do $.each(), e deve funcionar bem (independentemente de você estar usando o aval ou json.parse, mas eu recomendo o último).

Editado: já que você está usando jQuery.getJSON(), você não precisa usar eval ou JSON.parse - JQuery faz isso por você. Então, dentro da sua função de retorno de chamada, basta definir json = jsonData .

<script>
  var json;
  $(document).ready(function() { 
      jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
        json = jsonData;
        $.each(json, function (i, j) {
            document.index.user_spec.options[i] = new Option(j.options);
        });
      });
  });
</script>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top