【发布时间】:2022-01-04 12:27:15
【问题描述】:
我希望有人可以帮助对其进行排序,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>
【问题讨论】:
-
在 url 和 Json.parse(data) 之后尝试这些 dataType: "json", contentType: "application/json;charset=utf-8";成功
-
@SyedMuhammadShakaybAthar 设置
dataType: "json"的好主意,但如果服务器没有输出 JSON 开头(它不是),那么这一切都会在它发现时导致 JS 错误它无法解析数据。设置contentType是错误的,因为那是关于 AJAX 发送,而不是接收的内容。如果不清楚,可以在 JQuery $.ajax 文档中阅读。 -
你真的有一个叫做
die();的Javascript函数吗?它有什么作用?