如何加载使用jQuery和JSON数据? [英] How to load data using jQuery and JSON?

查看:89
本文介绍了如何加载使用jQuery和JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个MySQL数据库使用jQuery和JSON PHP页面加载数据。当用户选择的选择框中的名称,它加载了人的数据转换成文本字段。

I want to load data from a MySQL database to a PHP page using jQuery and JSON. When the user choose the name from the select box, it loads the person's data into the text field.

这是我的HTML code(选择)

This is my HTML code (select)

<select name='name' id='name'>
    <option value='1'>John</option>
    <option value='2'>Marco</option>
    <option value='3'>Charles</option>
</select>

这是我要填充与人数据的文本字段:

The text field that I want to populate with the person data:

<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>

getpersonData.php

<?php
    include('dbconfig.php');
    $id = $_POST['id'];
    $query = "select * from person where ID='$id'";
    $result = mysql_query($query);
    $data = mysql_fetch_array($result);

    echo json_encode($data);
?>

Ajax调用:

The Ajax call:

$.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);
    }
});

什么code,我应该使用的成功功能?

推荐答案

首先,你应该你回声你的内容类型头> json_en $ C $在C getpersonData.php

First, you should set your Content-type header right before you echo your json_encode in getpersonData.php:

header("Content-type: application/json");
echo json_encode($data);

在你的成功的功能,你会做这样的事情:

In your success function you would do something like:

$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query

这篇关于如何加载使用jQuery和JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆