2013-04-17 67 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');