2013-04-17 69 views
1

我是jQuery的新手,想知道如何从php文件中将数组键取回到jQuery中。如何在jQuery中从PHP获取数组密钥

我有这个jQuery代码来发布输入到file.php并exexute对每个键盘上的查询。

file.php呼应与阵列的帮助将是什么样子的结果:

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

jQuery的代码是:

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

所以,当我点击到li结果将被转换到文本中并且输入字段的值属性被填充。

举个例子:

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

将输出:

<li>ExAmpLE Home 2013</li> 

所以,当我点击li输入字段的新值:

例如首页2013

我的问题是我怎么能exlude特定阵列键,如$row["name"]$row["year"]从该点击功能结果值转换成文本,以便输入字段的新值:

例如,家庭

+0

Json是你的朋友 – mithilatw

回答

0

把你需要的东西进入跨度应该工作:

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

我假设你已经知道如何在li元素得到。然后做:

var $li= $(this); 
var text= $li.find('span').text(); 
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');