0

我是编程新手,我正在玩 htm/ajax/php。我有两个文本字段,名称和动物。您在名称字段中输入名称。如果名称存在于数据库中,它会返回与该名称相关的所有动物,并且不允许在动物字段中输入重复的动物。我正在使用LiveValidation进行验证。

到目前为止,我的名称字段工作正常。它正在检查数据库并返回与该名称关联的所有动物的逗号分隔列表,并将它们插入结果 div。然而,结果 div 仅用于测试。我想要的是结果列表在此处填充列表:

//animal must not include
var animal = new LiveValidation('animal');
animal.add(Validate.Exclusion, { 
    within: [
    // Insert ajax results here
    'cow' , 'pigeon', 'giraffe',
    ] 
} );

这是我的其余代码。我认为我想做的事情相当简单,我只是不知道该怎么做。感谢任何花时间帮助我的人。

HTML

<input type="text" id="name" name="name"/>
<input type="text" id="animal" name="animal" />
<div class="results"></div>   

JavaScript

<script>
    //ajax call
    $(function(){

        $('#name').blur(function(){
            var inpval = $('#name').val();

            $.ajax({
                type: 'POST',
                data: ({name : inpval}),
                url: 'name_taken.php',
                success: function(data) {
                    $('.results').html(data);
                }
            });
        });
    });

    //validation from livevalidation.com
    //name must be present
    var name = new LiveValidation('name');
    name.add(Validate.Presence);

    //animal must not include
    var animal = new LiveValidation('animal');
    animal.add(Validate.Exclusion, { 
        within: [
            // How do I insert ajax results here?
            'cow' , 'pigeon', 'giraffe',
        ] 
    } );
</script>

PHP

//name_taken.php
$input_name = trim($_POST['name']);

foreach($names_table as $row){
    $name = $row['name'];

    if($name == $input_name){
        echo $row['animal'] . ',';
    }
}

表结构

//$names_table
| 1 | Dave | animal1 |
| 2 | Mark | animal2 |
| 3 | Dave | animal3 |
4

1 回答 1

0

with your ajax function you can use dataType to set the return data type

//animal must not include
var animal = new LiveValidation('animal');
var obj = { 
    within: [
        'cow' , 'pigeon', 'giraffe',
    ] 
};
animal.add(Validate.Exclusion,  obj);

$.ajax({
    type: 'POST',
    data: ({name : inpval}),
    dataType: 'json',
    url: 'name_taken.php',
    success: function(data) {
        obj.within = new Array();
        for(var i in data){
            obj.within.push(data[i]);
        }
        animal.add(Validate.Exclusion,  obj);
    }
});

then in your php you just need to use json_encode() like this:

<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
于 2012-12-28T21:37:16.573 回答