Javascript 如何在wordpress中调用ajax
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43557755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call ajax in wordpress
提问by smarttechy
My ajax call output is always showing 0 as output don't know why
我的 ajax 调用输出总是显示 0 作为输出不知道为什么
In functions.phpI have this code
在functions.php我有这个代码
function get_data() {
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And my ajax call is in a javascript
我的 ajax 调用是在 javascript 中
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "GET",
dataType : "json",
url : "/wp-admin/admin-ajax.php",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.
我在不使用插件的情况下在 wordpress 中进行 ajax 调用,但没有得到我正在传递的内容。即使我输出 $abc 仍然显示 0。
回答by Vigneshwaran J
In backend there is global ajaxurl variable defined by WordPress itself.
在后端有由 WordPress 本身定义的全局 ajaxurl 变量。
This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.
这个变量不是由 WP 在前端创建的。这意味着如果你想在前端使用 AJAX 调用,那么你必须自己定义这样的变量。
Good way to do this is to use wp_localize_script.
这样做的好方法是使用 wp_localize_script。
Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:
让我们假设您的 AJAX 调用在 my-ajax-script.js 文件中,然后为这个 JS 文件添加 wp_localize_script,如下所示:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
本地化 JS 文件后,您可以在 JS 文件中使用 my_ajax_object 对象:
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});
回答by Philipp
Actually, WordPress comes with a handy function to access admin-ajax.
实际上,WordPress 带有一个方便的功能来访问 admin-ajax。
Requirements
要求
- In wp-adminyou do not need to do anything, the js library is always loaded
In the front-endyou need to enqueue the script
wp-util, like this:add_action( 'wp_enqueue_scripts', 'my_enqueue_function' ); function my_enqueue_function() { // Option 1: Manually enqueue the wp-util library. wp_enqueue_script( 'wp-util' ); // Option 2: Make wp-util a dependency of your script (usually better). wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] ); }
- 在wp-admin 中你不需要做任何事情,js 库总是被加载
在前端,您需要将脚本入队
wp-util,如下所示:add_action( 'wp_enqueue_scripts', 'my_enqueue_function' ); function my_enqueue_function() { // Option 1: Manually enqueue the wp-util library. wp_enqueue_script( 'wp-util' ); // Option 2: Make wp-util a dependency of your script (usually better). wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] ); }
The JS Library
JS 库
The wp-util script contains the wp.ajaxobject that you can use to make ajax requests:
wp-util 脚本包含wp.ajax可用于发出 ajax 请求的对象:
wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
Your example:
你的例子:
wp.ajax.post( "get_data", {} )
.done(function(response) {
alert("Your vote could not be added");
alert(response);
});
PHP code
PHP代码
Of course, you still need to create the wp_ajax_*hooks in your PHP script.
当然,您仍然需要wp_ajax_*在 PHP 脚本中创建钩子。
add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
function my_ajax_handler() {
wp_send_json_success( 'It works' );
}
Tip:
提示:
For Ajax responses WordPress provides two functions:
对于 Ajax 响应,WordPress 提供了两个功能:
wp_send_json_success( $my_data )and wp_send_json_error( $my_data )- both functions return a JSON object and instantly terminate the request (i.e., they exit;)
wp_send_json_success( $my_data )和wp_send_json_error( $my_data )- 两个函数都返回一个 JSON 对象并立即终止请求(即它们exit;)
回答by Shital Marakana
Add admin-ajax.phpby using admin_url('admin-ajax.php');
添加管理员-ajax.php使用admin_url('admin-ajax.php');
<script type="text/javascript">
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "POST",
dataType : "json",
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
</script>
回答by iamasp
<form type="post" action="" id="newCustomerForm">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email">Email:</label>
<input name="email" type="text" />
<label for="phone">Phone:</label>
<input name="phone" type="text" />
<label for="address">Address:</label>
<input name="address" type="text" />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>
functions.php
函数.php
wp_enqueue_script('jquery');
function addCustomer() {
global $wpdb;
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if ( $wpdb->insert( 'customers', array(
'name' => $name,
'email' => $email,
'address' => $address,
'phone' => $phone
) ) === false ) {
echo 'Error';
} else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
javascript
javascript
<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success: function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
回答by Awais Umar
If you are getting 0in the response, it means your ajax call is working correctly.
But, you have not defined $wpdb as a global variable in your function get_data.
Check your error log, you must be seeing error there.
Try:
如果您收到0响应,则表示您的 ajax 调用工作正常。但是,您还没有在函数 get_data 中将 $wpdb 定义为全局变量。检查您的错误日志,您一定在那里看到错误。尝试:
function get_data() {
global $wpdb;
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}

