前端包含一个按钮,用于调用js函数,然后调用php函数。这是根据我读到的关于php beeing服务器语言的内容,不能直接用于处理onclick事件。
因此,只需点击前端特定页面上的按钮,就会调用script.js函数onclick =“sendAjaxRequest(true);”
我的插件文件夹中有一个名为script.js的js文件,代码如下:
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' );
function sendAjaxRequest(value){
jQuery.ajax({
url: my_ajax_object.ajax_url,
type: 'POST',
data: ({action : 'get_my_option', value:value}),
success: function( response ) {
console.log( response );
}
});
}
php插件文件名为wsn-plugin.php,代码如下:
wp_enqueue_script('wsn-script', plugin_dir_url(__FILE__) . 'script.js');
wp_efunction your_function_name()
{
// wp_enqueue_script( 'myfunction', get_template_directory_uri().'/assets/js/applicantid.js', array( 'jquery' ), '1.0',true);
wp_localize_script( 'myfunction', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('template_redirect', 'your_function_name');
function get_my_option()
{
//get applicant id (looks like this is what you want to get back?)
//send json headers
header( "Content-Type: application/json" );
//print out you response as json
echo json_encode( $value );
//must have an exit in the ajax action callback!
exit();
}
add_action("wp_ajax_nopriv_get_my_option", "get_my_option");
add_action("wp_ajax_get_my_option", "get_my_option");nqueue_script('wsn-script');
通过单击按钮触发脚本后,我收到错误消息:“Uncaught SyntaxError:Unexpected string”,并且debuger在jquery.js文件中的特定点停止,如果我跳过这一点,那么它将转到下一个并且到下一个。
我错过了什么?
答案 0 :(得分:0)
完成后将php文件更改为:
<?php
/*
Plugin Name: WSN Plugin
description: Maintain all the connections to LimeSurvey
Version: 0.2
Author: M.Huber
Author URI: www.moritzhuber.ch
License: GPL2
*/
//reference to the backend ajax framework
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'test', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
// to reference the ajax call to this function
add_action( 'wp_ajax_nopriv_call_this', 'new_company_variable_transfer' );
function new_company_variable_transfer() {
echo 'Did we get here?';
wp_die();
}
并且js文件应该如下所示:
function callAjax(){
$.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{action:'call_this'},
success:function(response) {
alert(response);
$("#result").html(response);
}
});
}