我的网站上有一个地图搜索页面。我可以用HTML显示列表中的所有位置,但我很难同时将这些位置传递给JavaScript,以便在我的Google地图上填充PIN。
我似乎只能wp_localize_script
处理初始页面加载和AJAX调用期间的工作。
这是我的javascript:
jQuery(document).on( \'submit\', \'#locationsearch\', function() {
var form = jQuery(this);
var input = form.find(\'input[name="postcode"]\');
var query = input.val();
var map=jQuery(\'#map\');
var content = jQuery(\'#results\');
jQuery.ajax({
type : \'post\',
url : myAjax.ajaxurl,
data : {
action : \'getStockistLocations\',
query : query
},
beforeSend: function() {
console.log(\'fetching\');
input.prop(\'disabled\', true);
content.addClass(\'loading\');
},
success : function( response ) {
console.log(myAjax.locations);
input.prop(\'disabled\', false);
content.removeClass(\'loading\');
map.removeClass(\'hide-map\');
content.html( response );
}
});
return false;
});
我的console.log(myAjax.locations)
不断返回“未定义”。下面是我的PHP函数:
public function getStockistLocations(){
$postcode = $_POST[\'query\'];
$geocode=new Geocoder();
$lnglat = $geocode->geocodePostcode($postcode);
$results=$this->getStockists($lnglat);
if( !empty($results) ) {
wp_localize_script( \'main\', \'myAjax.locations\', $results );
ob_start();
foreach ($results as $result){
global $locationresult;
$locationresult=$result;
get_template_part(\'template_parts/cards/card\',\'location\');
}
$content = ob_get_clean();
echo $content;
}
die();
}
我正在另一个类中本地化脚本:protected function localizeScripts(){
global $post;
$mappages=[
\'contact\',
\'where-to-buy\',
\'find-an-installer\'
];
if(in_array($post->post_name,$mappages)){
$payload=array(
\'url\' => get_stylesheet_directory_uri(),
\'ajaxurl\' => admin_url(\'admin-ajax.php\'),
);
wp_localize_script( \'main\', \'myAjax\', $payload );
$key=$this->getAPIKeys(\'google\');
wp_enqueue_script(\'gmap\',\'https://maps.googleapis.com/maps/api/js?key=\'.$key.\'&callback=initMap\',null,false,true);
}
}
我错过了什么?