我有这些代码会显示带复选框的单词。正如您所看到的,它们以逗号分隔,并且我使用split()函数来爆炸字符串,使其成为一个数组。我用循环来迭代这些单词,但是我得到了一个"未定义的"对于这些话。它应该自动显示带复选框的单词,但单词显示undefined。当我点击刷新时,它会正确显示单词,并且有一个复选框。我不确定问题出在哪里。有什么想法吗?
$(document).on('click', '#wordlistsave', function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var word = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var words = word.split(", ");
for(var i = 0; i < words.length; i++)
{
var dataString = 'user='+user+'&title='+title+'&words='+words[i]+'&id='+postID;
<?php if (is_user_logged_in()): ?>
if(words[i])
{
$.ajax({
type: "POST",
url: "<?= plugins_url('wordlistsave.php', __FILE__) ?>",
data: dataString,
cache: true,
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", words[i]);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words[i]+'" style="cursor:pointer">\
<img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>\
  <input type="checkbox" name="words[]" value="'+ words[i]+ '">'+words[i] );
testBoxDiv.appendTo("#test_container");
}
});
}
<?php else: ?>
alert('Please login.');
<?php endif; ?>
}
});
答案 0 :(得分:1)
words
,但是当它执行时,您无法确定i
值,因为它不会同步执行。
因此,您可以将一个额外的参数,单词传递给ajax设置字典,并从成功函数中访问它。像这样:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: true,
word : words[i],
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", this.word);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+this.word+'" style="cursor:pointer"><img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>  <input type="checkbox" name="words[]" value="'+ this.word+ '">'+this.word );
testBoxDiv.appendTo("#test_container");
}
});
答案 1 :(得分:0)
此外,您不需要为$ .ajax构造数据字符串,您可以简单地传递数据:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: {
user: user,
title: title,
words: words[i],
id: postID
}