【问题标题】:Need JSON to pass values to AJAX from specific content type fields需要 JSON 将值从特定内容类型字段传递到 AJAX
【发布时间】:2012-09-26 15:23:41
【问题描述】:

我是 PHP 新手。

我想构建一个模块,我需要 json 来传递特定的内容类型字段。

我正在尝试这个,但我不知道如何处理回调函数。

这是我在 .js 中的 ajax

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


})

这是我在 .module 中的 php

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;
}

非常感谢您的建议。

【问题讨论】:

    标签: ajax json drupal drupal-7


    【解决方案1】:

    获得 JSON 响应后,您需要将其转换为 javascript 数组。为此,您可以这样做:

    var javaArray = $.parseJSON(data);
    

    现在您可以使用 javaArray['key1']['key2'] 等代码检索数据。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多