문제

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 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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top