Using jquery $ .post () to return multiple values

I am trying to use $ .post () as follows:

$.post("file.php", { file_id: $(this).val()}, function(data){...} Then it file.phpexecutes a database query and returns an array with a title, description and image link.

What I want to do is update the fields .val()for the form fields for each. I understand how to do this with one variable, it will be just the following:

$.post("file.php", { file_id: $(this).val()}, function(data){ 
   $('#title').val(data);
}

But how do I get the returned data for recognition in jquery as separate variables or as an array?

Thanks in advance

+3
source share
2 answers

$.post. . JSON, JavaScript.

$.post(
   "file.php", 
   { file_id: $(this).val() }, 
   function(data){ $('#title').val(data.title); $('#para').val(data.paragraph); },
   'json');

file.php -

<?php
$return_data=array('title'=>'Fishes Go To Market','paragraph'=>'Lots of stuff');

header('Content-Type: application/json');
echo json_encode($return_data);
exit();

(), jQuery , JSON, json_encode, .

. json_encode docs . , - () json_encoded , , JSON .

+7

- JSON. JSON ( ). .post(), JSON, , :

$.post("file.php", { file_id: $(this).val()}, function(data) { ... }, "json");

, :

$('#title').val(data.title);
$('#description').val(data.description);
+3

Source: https://habr.com/ru/post/1784304/


All Articles