开发者

using jquery $.post() for returning multiple values

开发者 https://www.devze.com 2023-02-03 18:36 出处:网络
I am trying to use a $.post() in the following way: $.post(\"file.php\", { file_id: $(this).val()}, function(data){...}

I am trying to use a $.post() in the following way:

$.post("file.php", { file_id: $(this).val()}, function(data){...} The file.php then does a database 开发者_StackOverflow中文版query and returns an array with a title, description and image reference.

What I want to do then is be able to update the .val() for form fields for each. I understand how to do this on a single variable, it would just be the following:

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

But, how do I get the data returned to be recognizable in jquery as either separate variables or as an array?

Thanks in advance


See the docs for $.post. The fourth parameter is the dataType. You can set this to JSON for your return data to be parsed into a JavaScript object or array.

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

In your file.php file, you can do something like

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

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

Be sure to include the header() so jQuery knows your data is supposed to be JSON, and to use json_encode so it is formatted properly.

See the json_encode docs for more info on that, and the docs on header. Remeber you can't have any other output come before your header() and printing the json_encoded data, or the header as well as the JSON will be invalid.


The easiest way is to pass back the values as JSON. You will need to convert your array to JSON on the server (there are lots of server-side libraries available for this). And modify your .post() method to return the data as JSON by adding a fourth parameter like:

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

You can then populate your variables as easily as:

$('#title').val(data.title);
$('#description').val(data.description);
0

精彩评论

暂无评论...
验证码 换一张
取 消