JSON.stringify (var) пуст, даже если консольный журнал говорит иначе - PullRequest
0 голосов
/ 31 октября 2019

Я работаю с angular, и у меня возникла проблема в разделе JQuery:

 console.log(sustancia); // responds with {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …} this is correct and its treated as an object

 console.log(JSON.stringify(sustancia)); // responds with {} making me unable to send it through a $.post

Я попытался сделать его в точности как предыдущий код, поместив его в массив, который даетта же проблема

Если я пытаюсь просмотреть его в журнале консоли, он работает, но если я пытаюсь использовать JSON.stringify, он ничего не возвращает.
Я попытался отправить его через $ .post без JSON.stringify, но это не сработало.
Вот часть кода:

$('.singlealta').on('mousedown',function(){
      var elementos = [];
      var sustancia = {};
	     $('#editorial >tr').click(function(){
         var id_sustancia = $(this).find('.id_sustancia').val();
         var comprado 		= $(this).find('.comprado').val();
         var usado			=$(this).find('.usado').val();
         var fecha 			=$(this).find('.fecha').val();
         var tipo_documento 		=$(this).find('.tipo_documento').val();
         var sedronar 			=$(this).find('.sedronar').val();
        sustancia = 
          { data:id_sustancia,comprado:comprado,usado:usado,fecha:fecha,documento:tipo_documento,sedronar:sedronar}
          elementos.push(sustancia);
          console.log(sustancia); //returns {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …}
 })
 console.log(JSON.stringify(elementos)); //returns []
 console.log(JSON.stringify(sustancia)); //returns {}
 
 $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends {} to the php file
 $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends [] to the php file
 
 console.log(elementos); //returns an array with the sustancia object below
 console.log(sustancia); //still returns {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …}
       });


До этого у меня был еще один почти идентичный JQuery, который прекрасно работает

$('#modificacion').on('mousedown',function(){
      var elementos = [];
      var i =0;
      $('#editorial >tr').each(function(){
      var id_sustancia 		=$(this).find('.id_sustancia').val();
      var comprado 		=$(this).find('.comprado').val();
      var usado			=$(this).find('.usado').val();
      var fecha 		=$(this).find('.fecha').val();
      var tipo_documento 	=$(this).find('.tipo_documento').val();
      var sedronar 		=$(this).find('.sedronar').val();
       if(i>=0){
	var sustancia = 
	{ data:id_sustancia,comprado:comprado,usado:usado,fecha:fecha,documento:tipo_documento,sedronar:sedronar}
	elementos.push(sustancia);
	console.log(elementos);    
       }
	i=i+1;
      });
      $.post("*myurl**/phpfile*",JSON.stringify(elementos));
     });
     //this one works pefectly and is not so diferent

есть идеи о том, что может вызвать возвращение JSON.stringify [] & {}?
спасибо заранее и извините, если у меня были грамматические ошибки, испанский - мой первый язык, но я не могу придумать, как его спросить.

1 Ответ

0 голосов
/ 31 октября 2019

Это происходит потому, что переменная просто имеет значение после какого-либо действия. При этом ваши переменные будут иметь значение после действия клика

$('#modificacion').on('mousedown',function(){
    $('#editorial >tr').click(function(){
        ...
        sustancia = {data:id_sustancia ...}
        elementos.push(sustancia);
        console.log(sustancia);

        // With this, the 'sustancia' just has value after click on '#editorial >tr'
        // so, the jQuery call this call back.
        // The result is there here inside the variable is asingn 
    });

    // But here happens in another momment,
    // It is call when 'mousedown'
    // The 'mousedown' happens before of 'click' in 'tr'
    console.log(JSON.stringify(elementos)); //returns []
    console.log(JSON.stringify(sustancia));
});

Правильный путь - это изменить ваш пост на действие клика, например:

$('#modificacion').on('mousedown',function(){
    $('#editorial >tr').click(function(){
        ...
        sustancia = {data:id_sustancia ...}
        elementos.push(sustancia);
        console.log(sustancia);

        // Now it works, because the click happens and asingn the variables
        $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends {} to the php file
        $.post("*myurl**/phpfile*",JSON.stringify(sustancia));
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...