我製作了一個帶有兩個選擇字段的表單。第一個字段由定製分類的父母填充。第二個領域填充每個人的孩子。我用AJAX來做到這一點,但似乎沒有工作。變化沒有任何反應。AJAX不能在選定的字段中工作 - 已更新
下面是我的PHP代碼:
function products_selection()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'category',
'hide_empty' => 0,
'exclude' => 1,1078,1079
);
$products = get_categories($args);
if ($products) {
echo '<select id="products-select">';
echo '<option selected="" disabled="" value="0"><span>Προϊόντα</span></option>';
foreach ($products as $product) {
echo '<option class="product-name" id="'. $product->term_id .'">'. $product->name .'</option>';
}
echo '</select>';
}
}
function nomoi()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'nomos',
'hide_empty'=> 0,
'parent' => 0
);
$categories = get_categories($args);
if ($categories) {
echo '<select id="nomoi-select">';
echo '<option selected="0" value="-1"><span>Νομοί</span></option>';
foreach ($categories as $category) {
$id = $category->term_id;
$name = $category->name;
$taxonomy = $category->taxonomy;
echo '<option class="nomos" id="'. $id .'">'. $name .'</option>';
}
echo '</select>';
}
echo '<select id="town-select">';
echo '<option selected="" disabled="" value="0"><span>Πόλεις</span></option>';
echo '</select>';
}
function my_ajax() {
if(isset($_POST['main_catid']))
{
$args = array(
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'name' => 'town-select',
'hierarchical' => 1,
'show_option_none' => 'Πόλεις',
'selected' => -1,
'child_of' => $_POST['main_catid'],
'echo' => 1
);
$categories = get_categories($args);
foreach ($categories as $cat) {
$cat_name = $cat->name;
$id = $cat->cat_ID;
echo '<option class="town" id="'. $category->id .'">'. $category->name .'</option>';
}
die();
} // end if
}
我的腳本:
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
$mainCat = $('#nomoi-select option:selected').attr('id');
console.log('$mainCat: ' + $mainCat);
// call ajax
$("#town-select").empty();
$.ajax
(
{
url:'index.php',
type:'POST',
// Use an object literal
data: {
"action" : "my_ajax()",
"main_catid" : $mainCat
},
success:function(results)
{
// alert(results);
alert('Successfully called');
$("#town-select").append(results);
},
error:function(exception)
{
alert('Exception: ' + exception);
}
}
);
});
});
以及註冊我的腳本功能:
function my_scripts() {
wp_enqueue_script('header-form', get_template_directory_uri() . '/js/headerform.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_scripts');
'#main_cat'是一個select?然後使用'var $ mainCat = $('#main_cat選項:選中').val();'來獲取所選選項的值。 – LinkinTED
沒有運氣。這是因爲它在表單或其他內容中? – vagelis
當你登錄'$ mainCat'時,控制檯說什麼? ('控制檯。($ mainCat)') – LinkinTED