我正在练习创建简单的ajax wordpress插件。我参考了wordress ajax文档和一些教程来创建插件。如何传递这些值以从php文件获得结果。与我在普通php中创建的代码一样,它工作得很好。我怎样才能解决这个问题。以下是我创建的代码。
index.php
<?php
/*
Plugin Name: Ajax Serach
*/
function my_assets() {
wp_enqueue_style( \'pubmed-style\', plugin_dir_url( __FILE__ ).\'css/pubmed-style.css\' );
wp_enqueue_script( \'pubmed-script\', plugin_dir_url( __FILE__ ).\'js/pubmed-script.js\', array(\'jquery\'), true );
wp_localize_script( pubmed-script, litsearch, array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' )));
}
add_action( \'wp_enqueue_scripts\', \'my_assets\' );
?>
<?php
function pubget(){
?>
<input type="text" name="" value="" id="sterm"/>
<input type="button" name="" value="Search term" id="pub_search"/>
<div id="container">olddata</div>
<?php
}
add_shortcode(\'pubajax\', \'pubget\');
?>
Test.php
<?php
class Testclass{
function infotext(){
$txt = \'This is a ajax response text\';
}
}
?>
Pub.php
<?php
function litsearch(){
$newterm = $_GET[\'nwterm\'];
$newtest = new Testclass();
if($newterm == $_GET[\'nwterm\']){
include(\'test.php\');
$newtest = new Testclass();
$newtest->infotext();
}
die();
}
add_action(\'wp_ajax_litsearch\', \'litsearch\');
add_action(\'wp_ajax_nopriv_litsearch\', \'litsearch\');
?>
mainjquery.js
jQuery( document ).ready(function(){
//alert("Jquery Loaded");
jQuery("#pub_search").click(function(){
alert("You clicked");
event.preventDefault();
var term= $("#sterm").val();
console.log(\'your term send: \'+term);
var data = {\'nwterm\': term }
$.get(litsearch.ajaxurl, data, function(data){
$("#container").html(data);
});
});
});
SO网友:Laxmana
在执行ajax调用时,必须将wp ajax操作的名称放入数据中。
我假设ajax url是正确的。
jQuery( document ).ready(function(){
//alert("Jquery Loaded");
jQuery("#pub_search").click(function(){
alert("You clicked");
event.preventDefault();
var term= $("#sterm").val();
console.log(\'your term send: \'+term);
var data = {\'nwterm\': term, \'action\': \'litsearch\'}
$.get(litsearch.ajaxurl, data, function(data){
$("#container").html(data.response);
});
});
});
另外,因为您想在html代码中添加响应,所以必须从服务器返回一些内容。
Test.php
<?php
class Testclass{
function infotext(){
$txt = \'This is a ajax response text\';
return $txt;
}
}
?>
Pub.php
<?php
function litsearch(){
$newterm = $_GET[\'nwterm\'];
$newtest = new Testclass();
$data = array();
if($newterm == $_GET[\'nwterm\']){
include(\'test.php\');
$newtest = new Testclass();
$data[\'response\'] = $newtest->infotext();
}
wp_send_json( $data );
}
add_action(\'wp_ajax_litsearch\', \'litsearch\');
add_action(\'wp_ajax_nopriv_litsearch\', \'litsearch\');
?>