我希望有人可以幫助排序,AJAX 只收到一個結果以顯示在選擇下拉串列中。它看起來像這個 Model1Model2Model3Model4。我想看起來像這樣
型號1
型號2
模型3
型號4
在 jquery 腳本上看起來像這樣:
$('#input_11_183').append('Model1');
$('#input_11_183').append('Model2');
$('#input_11_183').append('Model3');
$('#input_11_183').append('Model4');
所有這些資料都將添加到選擇下拉欄位
這是我的php代碼:
<?php
function list_of_brandcars() {
$model_option = $_POST['pass_data'];
$carposts = array(
'post_type' => 'list_of_cars',
'post_status' => 'publish',
's' => $model_option
);
$att = new WP_Query($carposts);
$count=0;
if($att->have_posts()){
while($att->have_posts()) : $att->the_post();
while(have_rows('mods')) : the_row();
echo get_sub_field('model');
endwhile;
endwhile;
}
die();
}
add_action('wp_ajax_nopriv_list_of_brandcars', 'list_of_brandcars');
add_action('wp_ajax_list_of_brandcars', 'list_of_brandcars');
?>
這是我的 jQuery 腳本
<script>
$(document).ready(function($) {
$('#input_11_11').change(function(){
var from_brand = $(this).val();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'list_of_brandcars',
pass_data: from_brand
},
success: function(data) {
$('#input_11_183').empty();
for (var i = 0; i < data.length; i ) {
$('#input_11_183').append('<option value="' data '">' data '</option>');
}
}
});
die();
});
});
</script>
uj5u.com熱心網友回復:
您正在輸出原始字串,這些字串只是連接在一起并成為回應中的一行文本。你需要輸出一些JSON格式的結構化資料。為此,首先創建一個陣列,然后將每段文本添加到該陣列中。
這是一個例子。我在代碼中添加或更改了某些內容的所有地方都添加了注釋:
PHP
$att = new WP_Query($carposts);
$count=0;
$response = array(); //make empty array
if($att->have_posts()){
while($att->have_posts()) : $att->the_post();
while(have_rows('mods')) : the_row();
$response[] = get_sub_field('model'); //add to the array
endwhile;
endwhile;
}
echo json_encode($response); //encode the array as JSON and output it
die();
JavaScript:
$.ajax({
type: 'POST',
url: ajaxurl,
dataType: "json", //tell jQuery to expect JSON in the response, and automatically parse it
data: {
action: 'list_of_brandcars',
pass_data: from_brand
},
success: function(data) {
$('#input_11_183').empty();
for (var i = 0; i < data.length; i ) {
$('#input_11_183').append('<option value="' data[i] '">' data[i] '</option>'); //access the correct element of (what is now) an array of strings.
}
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371475.html
標籤:php 查询 阿贾克斯 WordPress的
