我有以下Jquery代码,我试图根据区域值在$('.cbs-List').HTML(divHTML);
中显示信息。但是在成功函数中,我无法读取该区域的值,它指出
在这种情况下,将参数或值传递给成功函数的正确形式是什么?
$(document).ready(function() {
getSearchResultsREST('LA');
});
function getSearchResultsREST(region) {
var querySA = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA';
var queryDR = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM';
if(region == 'LA') {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + querySA + "'";
} else {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + queryDR + "'";
}
$.ajax({
url: searchURL,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
contentType: "application/json; odata=verbose",
success: SearchResultsOnSuccess(data, region),
error: function(error) {
$('#related-content-results').html(JSON.stringify(error));
}
});
}
function SearchResultsOnSuccess(data, region) {
var results;
var divHTML = '';
if (data.d) {
results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
if(results.length == 0) {
$('#related-content-results').html('There is No data for the requested query on ' + _spPageContextInfo.webAbsoluteUrl);
} else {
for (i=0; i<results.length; i++) {
var item = results[i];
var itemCell = item.Cells;
var itemResults = itemCell.results;
// Get values for item result
var _title = getValueByKey("Title", itemResults);
var _path = getValueByKey("Path", itemResults);
divHTML += '<li><a href=' + _path + '>' + _title + '</li>';
}
// Display information based on region.
$('.cbs-List').html(divHTML);
}
}
}
最佳答案
您有2个问题,而且它们都很容易解决。
region
传递给SearchResultsOnSuccess
。您已经可以在那里使用它了,因为它是在更高的范围内定义的。 $.ajax
的对象中,您没有将SearchResultsOnSuccess
设置为回调,而是在调用它。 更改行:
success: SearchResultsOnSuccess(data, region)
=> success: SearchResultsOnSuccess
function SearchResultsOnSuccess(data, region) {
=> function SearchResultsOnSuccess(data) {
它应该可以正常工作。
编辑:
这是您需要如何设置的基本示例
function search(region) {
$.ajax({
url: 'example.com',
method: 'GET',
success: successCallback,
});
function successCallback(data) {
console.log(data, region);
}
}
search('LA');