jquery post json data to PHP file

荒凉一梦 提交于 2020-02-04 23:04:27

问题


I have a click event where I compose a json data, then I want to POST it to a PHP file for processing. But something goes wrong. My PHP file is simplified for now looking like this:

<?php
header('Content-Type: application/json');
 var_dump($_POST);
?>

And the code for POST-ing looks like this:

// myarray is: var myarray = new Array(); 
// and it gets populated above this code

var strObj = JSON.stringify(myarray);
alert(strObj); // so far I get the alert containing valid JSON text
$.ajax ({
  type:"POST",
  url:"proces.php",
  contentType: "application/json",
  dataType: "json",
  async: false,
  data: strObj,
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});

So when I click the button, I receive the alert containing the JSON string (looks fine), then I get the alert saying "error", and when I check the console for the response of proces.php all I see is:

array(0) {
}

What am I doing wrong? What can I do to make it right?


回答1:


This did the trick for me:

$.ajax ({
  type:"POST",
  url:"proces.php",
  dataType: "json",
  async: false,
  data: {tmp: strObj},
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});



回答2:


I got an answer on my own. Seems to do the trick:

$.post("proces.php", {json: JSON.stringify(myarray)}, function(data){alert(data);});

I mean, I do not get the alert(data); (probably because I do not return a JSON back from php file) but in the PHP I can see the json data now.



来源:https://stackoverflow.com/questions/17592173/jquery-post-json-data-to-php-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!