社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

如何使用ajax从php推送到jquery数组?

rob.m mickmackusa • 4 年前 • 575 次点击  

我在服务器(php)上运行以下命令,在其中循环我的帖子并获取gmap字段中的一些坐标:

      $location = get_field('location');
      $lat = $location['lat'];
      $lng = $location['lng'];

然后我创建一对LAT和液化天然气坐标,如下所示:

      $coordinates = $lat.", ".$lng;
      echo $coordinates;

然后在javascript ajax成功的客户端上,我将这两对推送到一个数组中 var coords = []; 我在页脚有。

但我在控制台得到了一个奇怪的结果:

["4"]
(index):148 (2) ["4", "0"]
(index):148 (3) ["4", "0", "."]
(index):148 (4) ["4", "0", ".", "7"]
(index):148 (5) ["4", "0", ".", "7", "2"]
(index):148 (6) ["4", "0", ".", "7", "2", "7"]
(index):148 (7) ["4", "0", ".", "7", "2", "7", "2"]
(index):148 (8) ["4", "0", ".", "7", "2", "7", "2", "0"]...

这就是全部代码:

菲律宾比索

      function data_fetch(){
        $dates = $_POST['dates'];
        $dates = explode(',', $dates);
        $args = array(
          'meta_query' => array(
            array(
              'key' => 'anno',
              'value' => array($dates[0], $dates[1]),
              'compare' => 'BETWEEN',
              'type' => 'NUMERIC'
            ),
          )
        );
        $query = new WP_Query( $args );
        if( $query->have_posts() ): while( $query->have_posts() ) : $query->the_post();
          $location = get_field('location');
          $lat = $location['lat'];
          $lng = $location['lng'];
          $coordinates = $lat.", ".$lng;
          echo $coordinates;
        endwhile; endif;
        die();
      }

javascript

$(document).ready(function() {
  $("#searchNations").on("click", function() {
    //clearOverlays();
    fetch(datesSearch);
  });
  fetch(datesSearch);

  function fetch(datesSearch) {
    $.ajax({
      url: '<?php echo admin_url('
      admin - ajax.php '); ?>',
      type: 'post',
      dataType: 'json',
      data: {
        action: 'data_fetch',
        dates: datesSearch
      },
      success: function(data) {
        var data = $.parseJSON(data);
        for (var i = 0; i < data.length - 1; i++) {
          coords.push(data[i]);
          console.log(coords);
        };
      }
    });
  }
});
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47046
 
575 次点击  
文章 [ 1 ]  |  最新文章 4 年前
msg
Reply   •   1 楼
msg    4 年前

在php中,您将坐标作为字符串输出,但在javascript中将它们作为json处理。您必须将坐标推入数组并对其进行编码:

if( $query->have_posts() ): 
    $coordinates = [];
    while( $query->have_posts() ) : $query->the_post();
        $location = get_field('location');
        $lat = $location['lat'];
        $lng = $location['lng'];
        $coordinates[] = $lat.", ".$lng;
    endwhile;
    echo json_encode($coordinates);
    die;
endif;