使用jquery $ .post()返回多个值

时间:2011-01-08 21:49:00

标签: jquery variables .post

我试图以下列方式使用$ .post():

$.post("file.php", { file_id: $(this).val()}, function(data){...} 然后file.php执行数据库查询并返回带有标题,描述和图像引用的数组。

我想要做的是能够为每个表单字段更新.val()。我理解如何在单个变量上执行此操作,它只是以下内容:

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

但是,如何将返回的数据作为单独的变量或作为数组在jquery中识别?

提前致谢

2 个答案:

答案 0 :(得分:7)

the docs for $.post。第四个参数是dataType。您可以将其设置为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();

请确保包含header(),以便jQuery知道您的数据应该是JSON,并使用json_encode以使其格式正确。

有关详情,请参阅json_encode文档以及docs on header。记住你不能在header()之前有任何其他输出并打印json_encoded数据,或者标题以及JSON将无效。

答案 1 :(得分:3)

最简单的方法是将值作为JSON传回。您需要在服务器上将数组转换为JSON(有很多server-side libraries available for this)。并修改您的.post()方法,通过添加第四个参数来将数据作为JSON返回:

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

然后,您可以像以下一样轻松填充变量:

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