简体   繁体   中英

Jquery Post method and JSON issue

I'm using jquery and jason sending data to another contoller, but when I send the data, I check it in fire bug and it's fine, It sends it correctly but in the target page, when I var_dump the $_REQUEST or $_POST is returns null.

I'm using codeigniter by the way.

This my jquery code:

<script type="text/javascript">
function GetMovieLanguageCategory(Language) 
{
 $.ajax({
  type: "POST",
  contentType: "application/json",
  url: "/admin/movie/get_language_category",
  data: JSON.stringify({"Language":Language}),
  success: function(Data)
  {
    alert(Data);
  },
  failure: function(ErrorMsg) {
  alert(ErrorMsg);
  },
}); 
}
</script>

And in my Controller:

var_dump($_REQUEST);
//var_dump(json_decode($_POST['Language']));

And it returns:

array(0) {}

Am I wrong somewhere?

You are sending JSON data, but marking it as application/x-www-form-urlencoded data and you are trying to parse it as application/x-www-form-urlencoded data.

Change:

data: JSON.stringify({"Language":Language}),

to

data:{"Language":Language},

and let jQuery encode it properly for you.


If you want to encode it yourself (don't!):

data: "Language=" + encodeURIComponent(Language);

If you really want to send JSON:

contentType: "application/json",
data: JSON.stringify({"Language":Language}),

then, in the PHP, get the body of the request and run it through json_decode .

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