1

I'm new to jQuery and would like to know how I can fetch Array keys from a php file into jQuery.

I have this jQuery code to post input to file.php and exexute a query on every keyup.

file.php echoes the result with the help of an Array what will look like:

echo '<li>'.$row["name"].' '.$row["place"].' '.$row["year"].'</li>';

The jQuery code is:

$(document).ready(function() { //changes are possible when the page has fully loaded
    $('.inp').keyup(function() { //executes keyup function to the field class "inp"
        var inp = $(this).attr('value'); //sets a variable with the value of input from class="inp"
        $.post('ajax/file.php', {inp:inp}, function(data) { //posts that value to file.php as variable inp and executes the function (data) to this 
            $('.result').html(data);  //adds the returned result into HTML content as a first element in the set of class="result" => <li>

            $('.result li').click(function() { //executes click function when clicking li element
                var result_value = $(this).text(); //sets a variable and prepares something as text 
                $('.inp').attr('value', result_value); //fills value attribute of field class "inp" with the variable result_value
                $('.result').html(''); //clears li to ul class to hide the lists of results
            });
        });
    });
});

So when I click onto the li result it will be converted into text and the value attribute of the input field is filled with that.

To give an example:

echo '<li>'.$row["name"].' '.$row["place"].' '.$row["year"].'</li>';

will output:

<li>ExAmpLE Home 2013</li>

So when I click on li the new value of the input field is:

ExAmpLE Home 2013

My question is how can I exlude specific Array keys like $row["name"] or $row["year"] from converting the result value into text from that click function so that the new value of the input field is:

ExAmpLE Home

4

2 回答 2

2

您可以使用 json :

file.php

json_encode(array('name' => $row["name"], 'place' => $row["place"], 'year' => $row["year"]));

在您的 javascript 中使用 jQuery data()函数将您的数据存储在 DOM 中以便稍后检索它:

$.post('ajax/file.php', {inp:inp}, function(data) {
            $('.result').html(
              $('<li>').text(data.name + ' ' + data.place + ' ' + data.year)
                .data('name', data.name)
                .data('place', data.place)
                .data('year', data.year)
                .click(function() {
                    $('.inp').attr('value', $(this).data('name') + ' ' + $(this).data('place'))
                    $(this).empty();
                })
            );
        }, 'json');
于 2013-04-17T11:09:15.683 回答
0

将您需要的东西放入一个跨度应该可以工作:

echo '<li><span>'.$row["name"].' '.$row["place"].'</span> '.$row["year"].'</li>';

我假设您已经知道如何使用 li 元素。然后做:

var $li= $(this);
var text= $li.find('span').text();
于 2013-04-17T10:59:41.860 回答