猿问

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

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


      $location = get_field('location');

      $lat = $location['lat'];

      $lng = $location['lng'];

然后我像这样创建一对 lat 和 lng 坐标:


      $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"]...

所以这是整个代码:


PHP


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

        };

      }

    });

  }

});


江户川乱折腾
浏览 115回答 1
1回答

Qyouu

在 php 中,您将坐标作为字符串输出,但在 javascript 中将它们作为 json 处理。您必须将坐标推入数组并对其进行编码:if( $query->have_posts() ):&nbsp;&nbsp; &nbsp; $coordinates = [];&nbsp; &nbsp; while( $query->have_posts() ) : $query->the_post();&nbsp; &nbsp; &nbsp; &nbsp; $location = get_field('location');&nbsp; &nbsp; &nbsp; &nbsp; $lat = $location['lat'];&nbsp; &nbsp; &nbsp; &nbsp; $lng = $location['lng'];&nbsp; &nbsp; &nbsp; &nbsp; $coordinates[] = $lat.", ".$lng;&nbsp; &nbsp; endwhile;&nbsp; &nbsp; echo json_encode($coordinates);&nbsp; &nbsp; die;endif;
随时随地看视频慕课网APP
我要回答