【发布时间】:2015-03-30 13:44:27
【问题描述】:
我有一个由第 3 方脚本生成的搜索结果,我想向其中添加数据。我已解析结果以获取 id 数组,并在数据库中查询其他字段。 ajax 成功方法接收格式化的数组,但现在我被困在如何将这些结果放入 DOM 中的正确位置。
HTML:
<div class="ihf-results-property-info">
<div class="ihf-results-price">LIST: $2,150,000</div>
<div class="ihf-results-links"> <a href="#"> 24 Photos </a>
</div>
<div class="ihf-results-extra-info">
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
</div>
Repeat...
我在示例中包含的最后一个 div 具有我用于查询的唯一 ID。我想用它来将 ajax 返回与 DOM 中的正确位置相关联。这是我的javascript:
jQuery(document).ready(function($) {
// grab the listings numbers so we can query the db for extra data
var listings = $('.ihf-results-listingnum').map(function() {
// grab just the digits
var listingNum = $(this).text().replace(/[^0-9]/g, '');
// add the listing number to the parent so we can target it later
$( this ).parents('.ihf-results-extra-info').parent().addClass('marketing-details-' + listingNum);
return listingNum;
// use .get to create an array of the listing numbers
}).get();
$.ajax({
type: "GET",
url: "custom/07-idx-queries.php",
data: 'mlsNums=' + listings, // looks like ?mlsNums=735383,727468,699876...
success: function(result) {
// this logic came from here: http://stackoverflow.com/questions/15311320/how-to-work-with-jquery-ajax-and-php-array-return
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
jsObject = eval(resultJson);
jsArray = [];
for(elem in jsObject){
jsArray.push(jsObject[elem]);
}
console.log(jsArray);
// this works as expected, except keys are 0 based
// This is where it all falls apart. I want to extract each object and stick it in the DOM in the correct place
jQuery.each(jsArray, function(key, value) {
$( this ).appendTo('.marketing-details-' + key);
});
}
else {
console.log("error occurred");
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
})
});
我正在使用的 php 从 db 中产生所需的结果,但它是一个数字数组。我认为在尝试将结果放入 DOM 时,关联数组会更好地工作,这样我可以使用 ID 作为键并将它们与我添加的类匹配。以下是来自 custom/07-idx-queries.php 的相关代码:
$mls_nums = explode(",",$_GET['mlsNums']);
// removed all of the conditionals to keep the question clean
$html = array();
foreach ($mls_nums as $mls_num) {
// just retreiving a single object from each row for now
$remarks = $mysqli->query("SELECT mr FROM listings WHERE ln = '$mls_num'")->fetch_object()->mr;
// format the data
$my_html = "<p class='marketing-remarks mlsnum-".$mls_num."'>$remarks</p>";
// build an array of the results - necessary?
array_push($html,$my_html);
}
// send the data back in a JSON string
echo json_encode($html);
所以我的目标是查询数据库最多 10 行,并将结果插入到相同数量的新 div 中,这些新 div 是其类中具有相同 id 号的 div 的子级。我非常感谢任何帮助。
【问题讨论】:
-
我认为您应该只粘贴与您的问题相关的最少代码。如果问题与 ajax 相关,请粘贴该部分。