我在将最多6个URL导入ajax时遇到了一些困难。基本上你拿一个表单并在表单输入字段中输入一个URL。然后按'加载'。 jquery [参见JS#1 ]将获取输入的内容并加载Ajax调用。
但是,如果我按下“添加更多”按钮,它将添加多达5个输入字段。这里的问题是填充另外5个输入字段并按“加载”
它不会单独加载ajax URL。只是一个空数组。我做了一些关于延迟js加载的研究。但我显然没有做对。
然后我尝试了另一种方法[参见JS#2 ]。基本上手动编写ajax调用。这给了我更好的结果。但是,当我输入三个输入字段,然后按'加载'它然后只抓取一个输入字段并循环三次。
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="tFormBox">
<div class="tInputTop">
<h1>Add Up to 6</h1>
</div>
<div class="tInputBottom">
<label class="sr-only" for="cInput">Enter Name</label>
<div class="c-input-fields">
<div id="cInput">
<input class="form-control" name="cInput" placeholder="Enter Name">
<div class="add-more"></div>
</div>
</div><button id="chInputBtn">LOAD</button>
</div>
</div>
</body>
</html>
JS#1
var feed;
var sURLs = document.getElementsByClassName('cInput');
$('#cInput').click(function() {
$(this).toggleClass('focused');
})
$('#cInput > .add-more').click(function() {
// -- Limit to 6 more Additional Input Boxes --//
var i = $('.InputBottom div').length;
var cInput = $('<div id="cInput ' + i + ' "><input class="cInput" class="form-control" name="cInput" placeholder="Enter Name"></input></div>');
$.each(cInput, function(i, val) {
alert(cInput[i]);
});
if (i <= 7) {
console.log('adding')
$(cInput).appendTo('.c-input-fields');
} else {
console.log('maxed')
}
})
$('#cInput').on('click', function(tags) {
getS();
})
function getS() {
// --grab URLS to a maximum of 6 --//
for (var i = 0; i < sURLs.length; i++) {
var sValue = sURLs[i].value;
}
function multipleAjax(number, deferredObject) {
$.ajax({
url: '/' + 'sValue',
type: "GET",
success: function(data) {
results.push(data);
deferredObject.resolve();
}
});
}
var deferreds = [];
var results = [];
var nothingImportant;
for (var i = 0; i < nothingImportant; i++) {
var deferredObject = new $.Deferred();
deferreds.push(deferredObject);
multipleAjax(i, deferredObject);
}
// check if all ajax calls have finished
$.when.apply($, deferreds).done(function() {
console.log(results);
console.log(sValue)
});
}
JS#2
function getS() {
// --grab URLS to a maximum of 6 --//
for (var i = 0; i < sURLs.length; i++) {
var sValue = sURLs[i].value;
}
var async2 = $.ajax({
type: 'GET',
url: '/' + sValue,
success: function(data) {
console.log(data)
},
error: function(data) {
alert('notworking')
}
})
var async1 = $.ajax({
type: 'GET',
url: '/' + sValue,
success: function(data) {
console.log(data);
},
error: function(data) {
alert('notworking')
}
})
var async3 = $.ajax({
type: 'GET',
url: '/' + sValue,
success: function(data) {},
error: function(data) {
alert('notworking')
}
})
$.when(async3, async2, async1).done(function(result3, result2, result1) {});
}
答案 0 :(得分:0)
试试这个:
// --grab URLS to a maximum of 6 --//
var sValues = []; //array of urls
for (var i = 0; i < sURLs.length; i++) {
sValues[i].push(sURLs[i].value);
}
function multipleAjax(number, deferredObject) {
$.ajax({
url: '/' + sValues[number],
type: "GET",
success: function(data) {
results.push(data);
deferredObject.resolve();
}
});
}