【发布时间】:2019-01-15 08:41:32
【问题描述】:
所以基本上我有一个对 OS Maps(英国地图生成器)的 API 调用。根据他们的文档,我让它正常工作并且显示完美,但它是一个onload 事件,我在 WordPress 中使用 ACF(高级自定义字段)来显示基于自定义字段中使用的地图名称的地图。
问题是地图在页面加载时加载,但是在我的 Ajax 调用之后,当自定义地图名称等于 amlwch 时它不会加载。
发生这种情况是因为它是一个onload 事件,而 Ajax 显然不会重新加载页面,所以我只是不知道如何解决这个问题。
如果发生 Ajax 调用,如何让函数正常工作?
简而言之:
Ajax 不加载页面,因此在 ajax 调用后不会调用 body onload,我还有什么其他选项可以让它工作?
php:
(检查是否自定义字段名称,然后根据名称显示功能)
<!-- bodafon -->
<?php if( get_post_meta($postId,'route_map_name', true) == 'bodafon' ): ?>
<body onload="initmapbuilder()">
<div id="maproute" style=" width:100%; height:440px;"></div>
</body>
<!-- amlwch -->
<?php elseif( get_post_meta($postId,'route_map_name', true) == 'amlwch' ): ?>
<body onload="initmapbuilder1()">
<div id="maproute1" style=" width:100%; height:440px;"></div>
</body>
<?php endif; ?>
JS:
(AJAX,请记住它可以工作并显示此地图周围的所有数据,只是 onload 不工作)
/*Maps section ajax call*/
$(function(){
$('#routes').on('change', function(){
var that = $(this);
var post_id = that.attr('value');
// console.log(post_id);
$.ajax({
url:'../../wp-admin/admin-ajax.php', // admin-ajax.php will handle the request
type:'post',
data: {
// this is the action hook to call the handler "MyAjaxFunction"
action: 'post_maps_items',
// pass some data to post variblr to use in php/wordpress (optional)
id: post_id, // you can retrieve this using $_POST['id'];
},
timeout : 10000,
success:function(data){
// returned data by wordpress
//console.log('Success');
// $('#load_map').html(data);
$('#title').html(data).hide().fadeIn("slow").addClass('flex');
}
});
$.ajax({
url:'../../wp-admin/admin-ajax.php', // admin-ajax.php will handle the request
type:'post',
data: {
// this is the action hook to call the handler "MyAjaxFunction"
action: 'post_maps_items_info',
// pass some data to post variblr to use in php/wordpress (optional)
id: post_id, // you can retrieve this using $_POST['id'];
},
timeout : 10000,
success:function(data){
// returned data by wordpress
//console.log('Success');
$('#load_map').html(data);
// $('#title').html(data);
}
});
});
});
【问题讨论】:
-
为什么不在 ajax 成功后直接调用
initmapbuilder1() -
@emineminems 感谢您的回复,好吧,它基于自定义字段名称的内容,而不仅仅是这个 2 ,这只是作为示例。
标签: javascript html ajax advanced-custom-fields