2012-02-09 52 views
0

我需要从关联数组(PDO :: FETCH_ASSOC) 中获取数据,并将其放在下面的3个空文本字段中。 任何人都可以帮我一些代码。 在此先感谢。PDO :: FETCH_ASSOC到Jquery

尝试下面的例子中,没有运气:

$("#input-full-name").val(sport.values.full_name); 
$("#input-short-name").val(sport.values.short_name); 
$("#input-abb-name").val(sport.values.abbreviation); 

回答

0

好像你混淆服务器端和客户端操作。 PDO在服务器端运行并与数据库服务器通信。 JavaScript(在这种情况下,jQuery)在客户端运行并在DOM上运行。 AJAX是这两者之间的一种联系。

所以,如果你想填充输入字段与数据库中的一些值,你可以做到这一点,在服务器端:

<?php 
//run query, fetch array and store it in $sport 
?> 

<input type="text" name="full_name" value="<?php echo $sport['full-name']; ?>" /> 
<input type="text" name="short_name" value="<?php echo $sport['short-name']; ?>" /> 
<input type="text" name="abbreviation" value="<?php echo $sport['abb-name']; ?>" /> 

或者你可以做它的客户端(例如,如果用户点击一个链接/按钮/其他):

<?php 
//this is the script you make an AJAX-request to, e.g. get_data.php 

//run query, fetch array and store it in $sport 

echo json_encode($sport); //echo the array in JSON-format 

这是页面提供给用户:

... 
    <input type="text" name="full_name" id="input-full-name" value="" /> 
    <input type="text" name="short_name" id="input-short-name" value="" /> 
    <input type="text" name="abbreviation" id="input-abb-name" value="" /> 
... 
<button id="populate_btn">Populate Data</button> 

<scrip> 
    $('#populate_btn').click(functiion(){ 
    $.post('get_data.php', {}, function(sport) { 
     //sport now contains the json-array 
     $.each(sport, function(key, value) { 
     $('#input-'+key).val(value); 
     }); 
    }); 
    }); 
</script> 

这是一个非常基本的例子,但我希望你明白。还要注意,给定的AJAX示例仅适用于该数组的键匹配id-某种输入字段的属性,例如:$sport['full-name'] and <input id="input-full-name" />。这使得使用它变得更容易。