2012-09-26 26 views
2

對於PHP而言,我是新手。需要JSON才能將值從特定內容類型字段傳遞給AJAX

我想建立一個模塊,我需要json傳遞特定的內容類型字段。

我試着用這個,但我不知道如何處理回調函數。

這裏是我的.js

$.ajax({ 
    type: 'GET', 
    url: '/mappy/ajax/poi', 
    data: { 
    nid: nid 
    }, 
    dataType: 'json', 
    success: function(data){ 
    alert(data) 
    } 
}); 


}) 

阿賈克斯這裏是我在.module

function mappy_menu() { 
    $items = array(); 

    $items['/mappy/ajax/poi'] = array(
    'title' => 'Mappy Pois', 
    'page callback' => 'mappy_get', 
    'access arguments' => array('access content'), 
    'type' => MENU_CALLBACK, 
); 
    return $items; 
} 

function mpapy_get() { 

    $nid = $_GET('nid'); 
    $title = field_get_items('node', $node, 'field_title'); 
    $result = json_encode(
     db_query("SELECT nid,title FROM {node}", $nid) 
    ); 

    drupal_json_output($result); 
    print $result; 
} 

非常感謝意見PHP。

回答

0

的.js

$.ajax({ 
    type: 'GET', 
    // Do not use slash at the beginning, use Drupal.settings.basePath instead 
    url: Drupal.settings.basePath + 'mappy/ajax/poi', 
    data: { 
    nid: nid 
    }, 
    dataType: 'json', 
    success: function(data) { 
    alert(data) 
    } 
}); 

.module

function mappy_menu() { 
    $items = array(); 
    // Never use slash at the beginning in hook_menu 
    $items['mappy/ajax/poi'] = array(
    'title' => 'Mappy Pois', 
    'page callback' => 'mappy_get', 
    'access arguments' => array('access content'), 
    'type' => MENU_CALLBACK, 
); 
    return $items; 
} 

function mappy_get() { 
    $node = node_load($_GET('nid')); 
    // Or equivalent 
    /* $node = db_select('node', 'n') 
     ->fields('n', array('nid', 'title')) 
     ->condition('n.nid', $_GET('nid'))) 
     ->execute() 
     ->fetchAll(); */ 

    $values = array(
    'nid' => $node->nid, 
    'title' => $node->title 
); 

    #$result = json_encode(
    # db_query("SELECT nid,title FROM {node}", $nid) 
    #); 

    // drupal_json_output already print the value 
    // print $result; 

    drupal_json_output($values); 
    drupal_exit(); 
} 
+0

大。有用!謝謝弗拉德。 – Bojan

1

一旦獲得JSON響應,您需要將其轉換爲JavaScript數組。對於這一點,你可以這樣做:

var javaArray = $.parseJSON(data); 

現在你可以檢索數據,使用如下代碼javaArray [ 'key1的'] [ '密鑰2']等

相關問題