在你主插件或功能的PHP或任何你会做以下,以一个全局变量附加到某个脚本
$main_js_namespace = array(
'ajaxURL' => admin_url('admin-ajax.php'),
'data' => array(
'action' => '',
'method' => '',
'post' => '',
)
);
// script handler, javascript global variable name,
wp_localize_script('bec_script_handle','gVariable',$main_js_namespace);
该类类处理Ajax调用。
class ajaxClass {
public function __construct() {
// ajaxClass can be whatever you want..
add_action('wp_ajax_nopriv_ajaxClass', array($this, 'handle_ajax'));
add_action('wp_ajax_ajaxClass', array($this, 'handle_ajax'));
}
// this simply handle the routing of the functions.
public function handle_ajax() {
if(isset($_POST['method'])) {
$method = $_POST['method'];
if(method_exists($this, $method)) {
if(isset($_POST['post']) && $_POST['post'] != 'false') {
parse_str(stripslashes($_POST['post']), $post);
$request = call_user_func(array($this, $method), $post);
echo (is_array($request)) ? json_encode($request) : $request;
} else {
$request = call_user_func(array($this, $method));
echo (is_array($request)) ? json_encode($request) : $request;
}
} else {
$json['success'] = false;
$json['msg'] = __CLASS__.'::'.$method.' not found, define first! por favor..';
echo json_encode($json);
}
}
exit;
}
/*
* bla
* */
public function someAjaxCall($post){
$toRetun = "whatever Response You Want";
return $toRetun;
}
}
$ajaxClass = new ajaxClass();
//这是我怎么会打的电话到该脚本
// the action we chose
gVariable.data.action = 'ajaxClass';
// whatever method in the ajax class you want to access
gVariable.data.method = 'get_table_schema';
// whatever variable/data you want to pass
gVariable.data.post = 'tableName=' + tableName;
this functions is a async false and ones done give you an object with the result however any other would work.
var getData = function(){
var getData = {};
var setData = function(data) {
getData = data;
};
return function(){
$.ajax({
url: gVariable.ajaxURL,
type: "post",
async: false,
dataType:'json',
data:becGlobal.data,
success: function (data) {
setData(data);
},
error : function (data) {
setData(data);
}
});
return getData;
}
}
getData()();
</script>
仔细检查网址,可能问题出在哪里。 –
@NetaMeta我可以在浏览器中成功加载url,只需动态调用即可获得404。 –
是同一主机上的网址? –