我当前正在使用WP_Query
这将在按下按钮时从AJAX调用触发。post元字段lat
lng
将用作谷歌地图的位置数据。没有AJAX,查询输出很好,但似乎无法让它返回结果。
我收到的回复-[{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]
现在,我认为错误在于在以下位置将结果转换为JSONjson_encode
阶段,但不太确定?任何帮助都会很好,对AJAX来说都是全新的!
Function.php
<?php
//Search Function
function ek_search(){
$args = array(
\'orderby\' => \'date\',
\'order\' => $_POST[\'date\'],
\'post_type\' => \'property\',
\'posts_per_page\' => 20,
\'date_query\' => array(
array(
\'after\' => $_POST[\'property_added\']
),
),
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
$locations[] = array(
"name" => get_the_title(),
"lng" => get_field(\'loc_lng\'),
"lat" => get_field(\'loc_lat\')
);
}
$location = json_encode($locations);
echo $location;
die();
}
add_action( \'wp_ajax_nopriv_ek_search\', \'ek_search\' );
add_action( \'wp_ajax_ek_search\', \'ek_search\' );
Form
<form id="filter">
<button>Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
JS
jQuery(function($){
$(\'#filter\').submit(function(){
var filter = $(\'#filter\');
var ajaxurl = \'<?php echo admin_url("admin-ajax.php", null); ?>\';
data = { action: "ek_search"};
$.ajax({
url: ajaxurl,
data:data,
type: \'post\',
dataType: \'json\',
success: function(response) {
console.log(response);
}
});
return false;
});
});
最合适的回答,由SO网友:Johansson 整理而成
Admin AJAX未针对JSON进行优化。如果您需要JSON格式的答案,请改用REST-API。默认情况下,此API生成JSON响应。
您只需注册rest路由并访问URL:
add_action( \'rest_api_init\', function () {
//Path to REST route and the callback function
register_rest_route( \'scopeak/v2\', \'/my_request/\', array(
\'methods\' => \'POST\',
\'callback\' => \'my_json_response\'
) );
});
现在,回调函数:
function my_json_response(){
$args = array(
\'orderby\' => \'date\',
\'order\' => $_POST[\'date\'],
\'post_type\' => \'property\',
\'posts_per_page\' => 20,
\'date_query\' => array(
array(
\'after\' => $_POST[\'property_added\']
),
),
);
$query = new WP_Query( $args );
if($query->have_posts()){
while($query->have_posts()){
$query->the_post();
$locations[][\'name\'] = get_the_title();
$locations[][\'lat\'] = get_field(\'loc_lng\');
$locations[][\'lng\'] = get_field(\'loc_lat\');
}
}
//Return the data
return $locations;
}
现在,您可以通过访问以下URL获得JSON响应:
wp-json/scopeak/v2/my_json_response/
出于测试目的,您可以更改
POST
方法到
GET
并直接访问此URL。如果收到响应,请将其更改回
POST
并使用javascript。
仅此而已。