WordPress Ajax前端请求 后端接收数据
js
$("input[name='keywords']").bind('input propertychange', function() {
var keywords = $("input[name='keywords']").val();
if(keywords){
//ajax
$.ajax({
url: Auth_Object.ajax_url,
type: 'GET',
dataType: 'json',
data: {
"action": "ajax_location",
"_wpnonce": Auth_Object.nonce,
keywords: keywords
},
success: function(res){
if(res.status == 200){
arr=res.data.tips;
console.log(arr);
for(v=i=0; i<arr.length;i++){
students.innerHTML+="<td>"+arr[i].name+"</td>";//赋值<td>
}
}
}
});
}
});
后端
add_action('wp_ajax_nopriv_ajax_location', 'get_city_location');
add_action('wp_ajax_ajax_location', 'get_city_location');
function Cat_get_city_location(){
$keywords=$_GET["keywords"];
if($keywords!=''){
$urlPre='https://restapi.amap.com/v3/assistant/inputtips?output=json&city=028&keywords='.$keywords.'&key=xxx';
$data=file_get_contents($urlPre);
$json = json_decode($data,true);//将json解析成数组
$output = array("status"=>200,"data"=>$json);
echo json_encode($output);
die;
}else{
$data = array("code"=>"请输入");
$output = array("status"=>400,"data"=>$data);
echo json_encode($output);
die;
}
}