我在wordpress中创建了一个页面,该页面托管在localhost中。包含两个下拉列表的页面。一个是从名为“category”的表中选择类别列表,第二个下拉列表取决于第一个,即从“subcategory”表中选择子类别。类别id将添加到每个子类别值。子类别下拉列表的值取决于类别下拉列表,我尝试使用ajax实现这一点。
我的php文件test\\u ajax的代码。php
jQuery(document).ready( function(){
jQuery(\'#category\').on(\'change\',function (e){
e.preventDefault();
console.log("start1");
var catId = document.getElementById(\'category\').value;
console.log(catId);
jQuery.ajax({
type: \'POST\',
url: "/mudratcr/wp-admin/admin-ajax.php",
data: {\'key\':catId},
cache: false,
success : function (data) {
jQuery(\'#sub_cat\').html(data);
console.log(data);
}
});
});
});
</script>
<form method="post" name="myform" id="myform">
<table width="200" border="0" cellpadding="10">
<tr>
<th scope="col"> </th>
<th scope="col"> </th>
<th scope="col"> </th>
</tr>
<tr>
<td><label>Category</label></td>
<td><select name="category" id="category" >
<option value="">Select the category</option>
<?php
global $wpdb;
$result_fromDB = $wpdb->get_results("SELECT * FROM `category`");
foreach ($result_fromDB as $cat) {
echo "<option value=\'".$cat->id."\' selected>".$cat->name."</option>";
}
?>
</select>
</td>
<td></td>
</tr>
<tr>
<td><label>Sub Category</label></td>
<td>
<div id="fetch_data"><select name="sub_cat" id="sub_cat">
<option value=""> Select Sub category</option>
</select></div>
</td>
<td><div id="one"><span></span></div></td>
</tr>
</table>
</form>
功能。php——没有编写完整的代码。
function registerFormAction(){
// To handle the form data we will have to register ajax action.
$catid = $_REQUEST[\'catId\']; //catId is the value of category drop down list
}add_action(\'wp_ajax_nopriv_submitAjaxForm\',\'registerFormAction\');
add_action(\'wp_ajax_submitAjaxForm\',\'registerFormAction\');
当我运行此页面时,它显示错误的请求。谁能帮帮我吗。我是初学者。我读了很多关于ajax和word press的文章,但都不管用
SO网友:vikrant zilpe
This function will load the JS scripts:
function test_ajax_load_scripts() {
// load our jquery file that sends the $.post request
wp_enqueue_script( "ajax-test", plugin_dir_url( __FILE__ ) . \'/ajax-test.js\', array( \'jquery\' ) );
// make the ajaxurl var available to the above script
wp_localize_script( \'ajax-test\', \'the_ajax_script\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) ); }
add_action(\'wp_print_scripts\', \'test_ajax_load_scripts\');