简体   繁体   中英

Convert JavaScript object to JSON and POST it

I have to parse my html from and POST it to another script. When I use JSON.stringify to serialize object with parsed data, $_POST array in the receiving script is empty:

$("#addQueryForm").submit(function(event){
  event.preventDefault();
  result = {}     
  result['kindArr'];
  result['factor'];
  $("[rel=my-form]").each(function() {
    result[$(this).attr("name")] = $(this).attr("value");
  }); 
  var form = JSON.stringify(result);    
  $.post("add_kind.php", form , function(data) {
    alert(data);  
    //data shows me that $_POST array is empty
  }); 
});

But if I write json string into the query manually, it would be correct:

$.post("add_kind.php", {"kind":"Var1","kindArr":"Var12345","factor":"Var0","synonym1":"Var1","synonym2":"Var2","synonym3":"Var3"} , function(data) {
    alert(data);  
    //data shows me that $_POST contains posted data
});

What am I doing wrong?

PS: stringify was excess.

Maybe serialize would be better in your situation:

var form = $(this).serialize();    
$.post("add_kind.php", form, function(data) {
    alert(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM