我的UI上有一个按钮,当单击该按钮时,它会检查当前选项卡的URL,而不是从数据库传入的URL。如果它们匹配,我想调用一个函数进行ajax调用来获取一些数据。我的代码如下:
('#automate').click(automateButton);
function automateButton() {
if(webpageUrl == activeTabUrl){
//call function here
}
else {
// Window opens
window.open(webpageUrl);
}
}
这是我的ajax调用:
$('#scenarioDropdownList').change(function () {
var scenarioId = $('#scenarioDropdownList option:selected').attr('id');
getData(scenarioId);
});
function getData(scenarioId) {
$.ajax({
type: "GET",
url: 'http://localhost:54442/api/scenariodatas/GetScenarioData',
data: {scenarioId: scenarioId},
dataType: 'JSON',
success: scenarioData,
error: function(){
console.log("There has been an error retrieving the data");
}
});
}
function scenarioData(response) {
$.each(response, function(key, val) {
var fieldType = val.fieldType;
var fieldName = val.fieldName;
var fieldValue = val.fieldValue;
var field = $(fieldName);
})
}
我希望能够从if语句的内部调用ajax调用。我该怎么做?
当ajax调用独立时,编辑,并对返回正确数据的变量进行console.log。不幸的是,当我将其粘贴到if语句中或引用围绕它的函数时,这些值不会被记录下来。当ajax调用是独立的时,没有错误消息不能正常工作。
发布于 2020-01-20 12:47:53
您可以在if语句中直接使用$('#scenarioDropdownList').change();
触发事件change
:
$('#scenarioDropdownList').change(function () {
console.log("Calling ajax");
});
$('#automate').click(automateButton);
function automateButton() {
$('#scenarioDropdownList').change();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="scenarioDropdownList">
<option>foo</option>
<option>bar</option>
</select>
<button type="button" id="automate">Automate</button>
或将$('#scenarioDropdownList').change(function () { ... })
事件的内容移动到独立的函数中,您将从if语句中调用该函数
$('#scenarioDropdownList').change(ajaxCall);
$('#automate').click(automateButton);
function automateButton() {
ajaxCall();
}
function ajaxCall()
{
console.log("Calling ajax");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="scenarioDropdownList">
<option>foo</option>
<option>bar</option>
</select>
<button type="button" id="automate">Automate</button>
https://stackoverflow.com/questions/59823406
复制相似问题