Ajax 通信(Response = Answer) 完成

worldwithoutmin 67views 更新:2017年8月18日

(Download these & put in smartphoneApp -> index.html http://jquery.com/download/ https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js)

  1. smartphoneApp -> index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Title</title>

    <link rel="manifest" href="manifest.json">

    <!-- un-comment this code to enable service worker
    <script>
    if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("service-worker.js")
    .then(() => console.log("service worker installed"))
    .catch(err => console.log("Error", err));
}
</script>-->

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>

<!-- set up ajax -->
    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="jquery.xdomainajax.js"></script>

    <!-- Check if it reads jQuary file correctly
<script type="text/javascript">
$(document).ready(function() {
  alert("jQueryファイルの読み込み完了でーす。");
});
</script> -->

<!-- <script> var wp_url_admin_ajax = '<?php echo admin_url("admin-ajax.php"); ?>'; </script> -->
<script> var wp_url_admin_ajax = 'http://haritaipan.local/wp-admin/admin-ajax.php'; </script>
<script>
jQuery(function($) {
  $.ajax({
    crossDomain: true,
    type: "POST",
    url: wp_url_admin_ajax,
    data: {
      action: "tell_me"
    },

    success: function(response) {
      //console.log("ddd" + response);
      //json = JSON.parse(response);
      json = eval("(" + response + ")");
      if (json.err) {
        result = "error:404";
      } else {
        console.log(json);
      }
    }
  });
});
</script>

<!-- //start here -->
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
        <script type="text/javascript">
        var map_canvas;

function initialize_map() {
  var map_center = new google.maps.LatLng(35.6745973, 139.7778069);
  var map_options = {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: map_center,
    zoom: 14,
    mapTypeControlOptions: {
      mapTypeIds: [google.maps.MapTypeId.ROADMAP, "style"]
    }
  };
  map_canvas = new google.maps.Map(
    document.getElementById("map_canvas"),
    map_options
  );

  //マップの色や道路設定を変更しました。
  var mapstyle = [
    {
      stylers: [{ saturation: 33 }, { hue: "#0099ff" }, { lightness: -8 }]
    },
    {
      featureType: "poi",
      stylers: [{ visibility: "simplified" }]
    },
    {
      featureType: "transit.station.bus",
      stylers: [{ visibility: "off" }]
    },
    {
      featureType: "road.highway",
      stylers: [{ saturation: -48 }, { lightness: 42 }]
    }
  ];

  var myOptions = {
    name: "Blue"
  };

  var mapType = new google.maps.StyledMapType(mapstyle, myOptions);
  map_canvas.mapTypes.set("style", mapType);
  map_canvas.setMapTypeId("style");

  //Google mapで東京駅、大井町駅、八丁堀駅を3つマーカとして表す。
  var markerData = new Array();
  markerData.push({ lat: "35.681382", lng: "139.766084" });
  markerData.push({ lat: "35.684801", lng: "139.766086" });
  markerData.push({ lat: "35.6745973", lng: "139.7778069" });

  for (i = 0; i < markerData.length; i++) {
    create_marker(markerData[i].lat, markerData[i].lng);
  }
}

function create_marker(lat, lng) {
  var marker_options = {
    map: map_canvas,
    position: new google.maps.LatLng(lat, lng),
    zIndex: 0
  };

  var marker = new google.maps.Marker(marker_options);
}

google.maps.event.addDomListener(window, "load", initialize_map);
</script>

<!-- //end here -->

  </head>
  <body ng-app="starter">
    <!--
      The nav bar that will be updated as we navigate between views.
    -->
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>
    </ion-nav-bar>
    <!--
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).
    -->
    <ion-nav-view></ion-nav-view>
  </body>
</html>

admin-ajax.php

<?php
/**
 * WordPress Ajax Process Execution
 *
 * @package WordPress
 * @subpackage Administration
 *
 * @link https://codex.wordpress.org/AJAX_in_Plugins
 */

/**
 * Executing Ajax process.
 *
 * @since 2.1.0
 */

 header("Access-Control-Allow-Origin: *");

define( 'DOING_AJAX', true );
if ( ! defined( 'WP_ADMIN' ) ) {
    define( 'WP_ADMIN', true );
}

/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );

/** Allow for cross-domain requests (from the front end). */
send_origin_headers();

// Require an action parameter
if ( empty( $_REQUEST['action'] ) )
    die( '0' );

/** Load WordPress Administration APIs */
require_once( ABSPATH . 'wp-admin/includes/admin.php' );

/** Load Ajax Handlers for WordPress Core */
require_once( ABSPATH . 'wp-admin/includes/ajax-actions.php' );

@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
@header( 'X-Robots-Tag: noindex' );

send_nosniff_header();
nocache_headers();

/** This action is documented in wp-admin/admin.php */
do_action( 'admin_init' );

add_action('wp_ajax_tell_me', 'tell_me');  // ログイン状態のユーザーからのアクセスで動作する
add_action('wp_ajax_nopriv_tell_me', 'tell_me'); // 非ログインのユーザーからのアクセスで動作する
function tell_me() {
  $res = "answer";

  echo json_encode($res, JSON_UNESCAPED_UNICODE);

  die();
}

$core_actions_get = array(
    'fetch-list', 'ajax-tag-search', 'wp-compression-test', 'imgedit-preview', 'oembed-cache',
    'autocomplete-user', 'dashboard-widgets', 'logged-in',
);

$core_actions_post = array(
    'oembed-cache', 'image-editor', 'delete-comment', 'delete-tag', 'delete-link',
    'delete-meta', 'delete-post', 'trash-post', 'untrash-post', 'delete-page', 'dim-comment',
    'add-link-category', 'add-tag', 'get-tagcloud', 'get-comments', 'replyto-comment',
    'edit-comment', 'add-menu-item', 'add-meta', 'add-user', 'closed-postboxes',
    'hidden-columns', 'update-welcome-panel', 'menu-get-metabox', 'wp-link-ajax',
    'menu-locations-save', 'menu-quick-search', 'meta-box-order', 'get-permalink',
    'sample-permalink', 'inline-save', 'inline-save-tax', 'find_posts', 'widgets-order',
    'save-widget', 'delete-inactive-widgets', 'set-post-thumbnail', 'date_format', 'time_format',
    'wp-remove-post-lock', 'dismiss-wp-pointer', 'upload-attachment', 'get-attachment',
    'query-attachments', 'save-attachment', 'save-attachment-compat', 'send-link-to-editor',
    'send-attachment-to-editor', 'save-attachment-order', 'heartbeat', 'get-revision-diffs',
    'save-user-color-scheme', 'update-widget', 'query-themes', 'parse-embed', 'set-attachment-thumbnail',
    'parse-media-shortcode', 'destroy-sessions', 'install-plugin', 'update-plugin', 'press-this-save-post',
    'press-this-add-category', 'crop-image', 'generate-password', 'save-wporg-username', 'delete-plugin',
    'search-plugins', 'search-install-plugins', 'activate-plugin', 'update-theme', 'delete-theme',
    'install-theme', 'get-post-thumbnail-html', 'get-community-events',
);

// Deprecated
$core_actions_post[] = 'wp-fullscreen-save-post';

// Register core Ajax calls.
if ( ! empty( $_GET['action'] ) && in_array( $_GET['action'], $core_actions_get ) )
    add_action( 'wp_ajax_' . $_GET['action'], 'wp_ajax_' . str_replace( '-', '_', $_GET['action'] ), 1 );

if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], $core_actions_post ) )
    add_action( 'wp_ajax_' . $_POST['action'], 'wp_ajax_' . str_replace( '-', '_', $_POST['action'] ), 1 );

add_action( 'wp_ajax_nopriv_heartbeat', 'wp_ajax_nopriv_heartbeat', 1 );

if ( is_user_logged_in() ) {
    /**
     * Fires authenticated Ajax actions for logged-in users.
     *
     * The dynamic portion of the hook name, `$_REQUEST['action']`,
     * refers to the name of the Ajax action callback being fired.
     *
     * @since 2.1.0
     */
    do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
    /**
     * Fires non-authenticated Ajax actions for logged-out users.
     *
     * The dynamic portion of the hook name, `$_REQUEST['action']`,
     * refers to the name of the Ajax action callback being fired.
     *
     * @since 2.8.0
     */
    do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
// Default status

die( '0' );

ログイン / 新規登録してコメントする

このソースコードをストックして後で利用したり、作業に利用したソースコードをまとめることができます。

こちらもお役に立つかもしれません