如何使用jQuery和JSON加载数据?
我想使用jQuery和JSON将数据从MySQL数据库加载到PHP页面。 当用户从选择框中选择名称时,它会将人员的数据加载到文本字段中。
这是我的HTML代码(选择)
John Marco Charles
我想用人员数据填充的文本字段:
getpersonData.php
Ajax调用:
$.ajax({ type: "POST", async : false, url: 'http://test.com/getpersonData.php', dataType: 'json', data : { id : $("#id").val(), }, success : function(data) { //What to insert here? }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown); } });
我应该为success
函数使用什么代码?
首先,您应该在getpersonData.php
回显json_encode
之前设置Content-type
标头:
header("Content-type: application/json"); echo json_encode($data);
在您的成功function中,您可以执行以下操作:
$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query
我在这里猜你的数据库列名,但也许是这样的
$('#firstname').val(data.firstname); $('#phonenum').val(data.phonenum);
getpersonData.php
主文件
Load JSON data through jQuery and PHP